多语言展示
当前在线:814今日阅读:183今日分享:45

C#调用C++dll

C#调用C++dll的方法和步骤其他分享涉及到的概念和方法对于像我这样比较菜的选手看起来比较费劲并且很难抓住重点,这里我总结了一段时间的研究成果供初学者救济之用,简单明了。
工具/原料

VS2008

方法/步骤
1

新建项目->Visual C++->Win32项目 MyDLL注意:C++编写的dll一般是不能直接拿来C#调用,需要先新建个C++的工程把dll里的方法重新封装成可被C#外部调用的函数。

2

MyDLL.cpp里的代码如下:extern "C"  _declspec(dllexport)int add(int a ,int b)  {   int sum=a+b; return sum;}注意:函数前一定要加extern "C"  _declspec(dllexport),可被外部引用

3

项目->属性->常规->公共语言运行库支持->公共语言运行库支持(/clr)

4

F5编译程序,在Debug文件夹中找到生成MyDLL.dll目标文件备用

方法/步骤2
1

新建项目->Visual C#->控制台应用程序 dllConsoleApplication1

2

将步骤1生成的MyDLL.dll文件copy到dllConsoleApplication1工程的根目录下

3

Program.cs代码如下using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.InteropServices;   //必须添加,不然DllImport报错namespace dllConsoleApplication1{    class CPPDLL    {        [DllImport("MyDLL.dll", CharSet = CharSet.Ansi)] //引入dll,并设置字符集        public static extern int add(int a ,int b);    }    class Program    {        static void Main(string[] args)        {            int sum=CPPDLL.add(3, 4);        }    }}

4

编译程序,在程序中加断点,查看函数的计算结果

5

到这里,C++dll里的方法已经在C#里调用成功了。

注意事项

如果你的C++dll里还调用了其他的dll文件那么需要把调用的其他dll文件也加到C#工程的根目录里,不然就会报错找不到MyDLL.dll模块。

推荐信息