開發環境:
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,運行控制台項目,項目正常運行!