c#调用托管dll

来源:互联网 发布:双11淘宝每年销售额 编辑:程序博客网 时间:2024/05/29 18:23

调用方法:
1.项目右键,添加引用,选择你c#写的dll
2.直接通过命名空间.类名.方法,就可以用了,举例:

 

dll 内容为:

using System;
using System.Collections.Generic;
using System.Text;

namespace TPalg // Algorithm For Targeting Soft
{
    public class ClassALG
    {
        public static void Main(string[] args)
        {

        }
        public static int MainALG(int myi)
        {
            int sum;
            sum = 0;       //累加变量赋初始值
            
            for (int i = 1; i <= 100; i++)
            {   //循环体
                sum = sum + i;  //累加求和
            }
            return sum;
        }
    }
}

在C#里面调用,要在工程引用上点右键,添加引用,把dll引用进来。 后编写代码:

        using System.Runtime.InteropServices;   //支持调用托管dll类的命名空间

        using TPAlg; //dll的命名空间

        private void button8_Click(object sender, EventArgs e)
        {
            int xx;
            ClassALG tpalg = new ClassALG();
            xx=tpalg.MainALG(2);
            label6.Text=xx.ToString();
        }



别的语言,所有的windows下的dll,exe都要符合pe文件格式,才可以被系统调用。但是.net托管程序的dll和exe,不是标准的pe结构,而是启动后,执行了.net clr。所以不能用标准的pe可执行文件的调用方式。方法不同而已。
非托管程序调用c#的dll方法详见google : c++ 调用 c# dll

原创粉丝点击