2013年5月2日 星期四

C#中呼叫C++ DLL(VS2010 + OpenCV2.4)

將C++封裝成DLL檔

  1. 建立win32控制專案,應用程式類型選擇為"DLL"
  2. 加入函式內容CPP檔
  3. 在主程式函式前加上 extern "C" __declspec(dllexport)
    例: 
    extern "C" __declspec(dllexportvoid myFunction(...) {...}
  4. 編譯成功後在Debug(Release)資料夾中生成DLL數個相關檔案
  5. DLL封裝完成

C#呼叫DLL函式

  1. 建立新C# Windows Form專案
  2. 將封裝的DLL所有檔案放到bin->Debug資料夾下
  3. form1.cs中加入 using System.Runtime.InteropServices;
  4. 宣告DLL中要使用的函示
    [DllImport("myFunction.dll")] public static extern void myFunction(...)
    參數內容與C++宣告相同,些許地方改變,
    陣列"[ ]"接在參數型態後,例: 
    char name[] -> char[] name
    "*"和"&"更改為ref,例: int &x -> ref int x
    程式中使用DLL函式,參數有宣告為ref時,呼叫時該參數前也需要加上ref
  5. 讀取圖片應放在DLL路徑下
  6. 執行一半跳出"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)

沒有留言:

張貼留言