C#调用C++动态库(dll)

1.先创建一个C++空的动态库

  

2.修改2个属性

  (1)设置公共语言运行时支持,目的是将C++代码编译成为中间语言(clr),

    

  (2)

    

3. main.h中:

  #pragma once
  #include <string>

  //在被导出的函数前面一定要添加额extern “C来指明导出函数的时候使用C语言方式编译和链接的,这样保证函数定义的名字相同,否则如果默认按C++方式导出,那个函数名字就会         //变得乱七八糟,我们的程序就无法找到入口点了

       //__declspec(dllexport)”意思是将后面修饰的内容定义为DLL中要导出的内容

  _EXTERN_C     __declspec(dllexport) int FuncAdd(int a, int b);                            

  };

4.main.cpp中:

  #include "main.h"

  __declspec(dllexport)  int  FuncAdd(int a, int b)
  {
    return a + b;
  }

5. 创建C#工程,去调用dll

  public class Program
  {
    [DllImport(@"ConsoleApplication1.dll", EntryPoint = "FuncAdd", CallingConvention = CallingConvention.Cdecl)]
    public extern static int FuncAdd(int a,int b);
    static void Main()
    {
      int temp = FuncAdd(1, 2);
      Console.WriteLine(temp);

    }

       }

111
原文地址:https://www.cnblogs.com/zwj-199306231519/p/11128071.html