- C# 調用 C++ 函數實現方法
C# 調用 C++ 函數比較複雜的是結構體的封裝,一般數據類型可以簡單地轉換爲C# 的數據類型即可,對於結構體類型的傳遞或者是結構體中包含指針,結構體嵌套傳遞都會比較複雜、
結構體傳遞的方法例子:
C# 函數封裝C++ 結構體 參考
https://blog.csdn.net/sdl2005lyx/article/details/6801113
圖像二值化函數的C++接口封裝例子:
C++ 函數接口
struct ImageRoi
{
int x=0; //!< x coordinate of the top-left corner
int y=0; //!< y coordinate of the top-left corner
int width=0; //!< width of the rectangle
int height=0; //!< height of the rectangle
bool isSetRoi = 0;
};
struct ImageInfo
{
int width=0;
int height = 0;
int pixelFormat= Gray8;
};
extern "C" __declspec(dllexport) int thresholdImage(Byte* srcData, ImageRoi roi, ImageInfo imginfo, int lowT, int highT, Byte* binData, Byte* resultData,bool isrpy);
C# 部分的接口代碼:
public struct ImageRoi
{
public ImageRoi(int x, int y, int w, int h,bool isSetRoi)
{
_x = x;
_y = y;
_width = w;
_height = h;
_isSetRoi = isSetRoi;
}
public int _x;
public int _y;
public int _width;
public int _height;
public bool _isSetRoi;
};
public struct ImageInfo
{
public ImageInfo(int w, int h, MyImageFormat px)
{
_width = w;
_height = h;
_pixelFormat = (int)px;
}
public int _width;
public int _height;
public int _pixelFormat;
}
[DllImport(dllpath, EntryPoint = "thresholdImage", CallingConvention = CallingConvention.Cdecl)]
public static extern int thresholdImage(IntPtr srcData, ImageRoi roi, ImageInfo imginfo, int lowT, int highT, IntPtr binData, IntPtr resultData, bool isrpy);
其中圖像數據指針即可以是IntPtr類型 ,也可以是byte[] (在C#代碼中爲字節數組指針);
結構體的定義和C++類似,傳遞的時候屬於值傳遞,
圖像數據返回也採用指針,在C#上層對數據進行轉化顯示結果圖像。