C#调用C++的dll

C#调用C++的dll两种方法

一、使用非托管类调用C++dll

1、首先在vs2010新建项目选择win32应用程序,并设置为DLL,如下图所示
2、添加MyDLL.cpp源文件,其中代码:
extern "C" __declspec(dllexport)int add(int a, int b)
{
    return a + b;
}

extern "C"外部声明,表示函数和变量是按照C语言的方式编译和链接的。

__decspec(dllexport)的目的是为了将对应的函数放入到DLL动态库中。

extern "C" _declspec(dllexport)的目的是为了使用DllImport调用非托管C++的DLL文件。因为使用DllImport只能调用由C语言函数做的DLL。

3、设置项目MyDLL->属性->配置属性->公共语言运行时支持->公共语言运行时支持(、\clr)编译,将生成的dll(debug目录下 )

如果在编译时没有选择公共语言支持,会报错没有COM 引用

4、新建 C#控制台应用程序 dllConsoleApplication1 添加引用 ->浏览->选择生成的DLL添加 将上文所生成的 DLL拷贝到C#应用程序的bin里面然后应用如下方式进行调用:
5、新建一个C# windows 应用


6、新建一个按钮

using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
     
        private void button1_Click(object sender, EventArgs e)
        {

            int c=cppddl.add(10, 20);
          
        }
    }
    class cppddl
    {
        [DllImport("DLL1.dll")]
        public static extern int add(int a, int b);
   
    }

}
在调用函数前需要对C语言函数进行引用,如上面class 红色部分
7、

此时调用函数是会报错误
对 PInvoke 函数“WindowsFormsApplication1!WindowsFormsApplication1
这里要注意:


解决办法:

调试-》异常-》manager debug assistants-》PInvoke stackimblance 后面的“引发”勾去掉