C#调用C++dll

C#调用C++dll的方法和步骤

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

工具/原料

 
  • VS2008

方法/步骤

 
  1.  

    新建项目->Visual C++->Win32项目 MyDLL

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

    C#调用C++dll
    C#调用C++dll
  2.  

    MyDLL.cpp里的代码如下:

    extern "C"  _declspec(dllexport)int add(int a ,int b)  

    {  

    int sum=a+b;

    return sum;

    }

    注意:函数前一定要加extern "C"  _declspec(dllexport),可被外部引用

    C#调用C++dll
  3.  

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

    C#调用C++dll
  4.  

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

    C#调用C++dll
    END

方法/步骤2

 
  1.  

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

    C#调用C++dll
  2.  

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

    C#调用C++dll
  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. 4

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

    C#调用C++dll
  5. 5

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

原文地址:https://www.cnblogs.com/bruce1992/p/14290281.html