C#调用C++导出(dllexport)方法

开发环境:

visual studio 2013+win10

一:建立C++项目

在vs中建立C++project(Win32 Project),需要注意的是,要勾选:

  Application type:Dll

  Additional options:Export symbols

在项目头文件中放入代码:

#define WAOCVDLL_API __declspec(dllexport)
// 自定义方法
EXTERN_C WAOCVDLL_API int _stdcall Fit(int width, int height, wchar_t*image, float*firstPoint, int pointsLength);

然后再cpp文件中实现该方法:

WAOCVDLL_API int _stdcall Fit(int imageWidth, int imageHeight, wchar_t*image, float*firstPoint, int pointsLength)
{
// 实现代码
}

 ps:WAOCVDLL_API 因各自项目不同而不同

在编译之前需要设置项目属性:

C/C++ --> Advanced --> Compile As:Compile as C++ code

ps:C++项目的平台结构一定要和调用项目的一致(若是x64就都是x64,反之亦然)。

OK,build项目,得到dll

二:建立调用项目(C#控制台)

调用时需要注意的是:

[DllImport(@"你的dll存放路径", EntryPoint = "C++中定义的方法名字")]
extern static unsafe int Fit(int width, int height, char* image, float* firstPoint, int pointsLength);

之后就是在C#中调用非托管代码了,需要注意的是:

  1.设置项目属性:Allow unsafe code

  2.代码中添加unsafe代码块

OK,运行控制台项目,项目正常运行!

原文地址:https://www.cnblogs.com/Pure-Land/p/4951067.html