C#调用C++ Dll内存指针报内存错误
C++代码如下:extern "C" __declspec(dllexport) void _cdecl Test(char* path, int& width, int& height, int& step,uchar*& data)
{
Mat thresholdImg, img = imread(path, IMREAD_GRAYSCALE);
uchar* imgdata = new uchar[img.rows*img.cols*3];
imgdata = img.data;
width = img.size().width;
height = img.size().height;
step = img.step;
data = imgdata;
}
C# 代码如下:
public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count);
[DllImport("MyDll.dll", EntryPoint = "Test",CallingConvention = CallingConvention.Cdecl)]
private static extern void Test(string path, ref int width, ref int height, ref int step,ref IntPtr imgdata);
private void button1_Click(object sender, EventArgs e)
{
int width = new int();
int height = new int();
int step = new int();
IntPtr imgData = new IntPtr();
string imgPath = @"E:\OpenCV\WindowsFormsApp1\WindowsFormsApp1\bin\x64\Debug\picture.bmp";
Test(imgPath, ref width, ref height, ref step, ref imgData);//调用C++ dll
Bitmap bmp = new Bitmap(width, height, step, System.Drawing.Imaging.PixelFormat.Format8bppIndexed, imgData);//绘制图片
bmp.Save(@"E:\OpenCV\WindowsFormsApp1\WindowsFormsApp1\bin\x64\Debug\test.bmp");//保存图片
}
但是C#在" bmp.Save(@"E:\OpenCV\WindowsFormsApp1\WindowsFormsApp1\bin\x64\Debug\test.bmp");//保存图片" 的地方会报"尝试读取受保护的内存"
请问各位大神,有没有什么好的方法解决?