- 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#上层对数据进行转化显示结果图像。