將C++封裝成DLL檔
- 建立win32控制台專案,應用程式類型選擇為"DLL"
- 加入函式內容CPP檔
- 在主程式函式前加上 extern "C"
__declspec(dllexport)
例: extern "C" __declspec(dllexport) void myFunction(...) {...} - 編譯成功後在Debug(Release)資料夾中生成DLL數個相關檔案
- DLL封裝完成
C#呼叫DLL函式
- 建立新C# Windows Form專案
- 將封裝的DLL所有檔案放到bin->Debug資料夾下
- form1.cs中加入 using System.Runtime.InteropServices;
- 宣告DLL中要使用的函示
[DllImport("myFunction.dll")] public static extern void myFunction(...)
參數內容與C++宣告相同,些許地方改變,
陣列"[ ]"接在參數型態後,例: char name[] -> char[] name
"*"和"&"更改為ref,例: int &x -> ref int x程式中使用DLL函式,參數有宣告為ref時,呼叫時該參數前也需要加上ref - 讀取圖片應放在DLL路徑下
- 執行一半跳出"PInvokeStackImbalance"警告視窗,點選繼續仍可成功執行
debug -> exception -> managed debugging assistants -> PInvokeStackImbalance 的 Thrown 勾取消忽略訊息
C#使用OpenCV
form1.cs中加入
using Emgu.CV.Structure;
using Emgu.CV.UI;
using Emgu.CV;
using Emgu.CV.CvEnum;
參考中加入上述檔案路徑(libemgucv)
沒有留言:
張貼留言