尝试读取或写入受保护的内存.这通常表示其他内存已损坏.在C++Dll中

Attempted to read or write protected memory. This is often an indication that other memory is corrupt. in C++ Dll

本文关键字:内存 表示 其他 C++Dll 已损坏 常表示 读取 受保护      更新时间:2023-10-16

我的代码有问题。当我编译程序时,它会写"AccessViolationException未处理"试图读取或写入受保护的内存。这通常表明其他内存已损坏。">

C#代码:

[DllImport(@"DLLmedian.dll")]
public static extern SCIOX_bitmap median(SCIOX_bitmap image, int size);
private void button2_Click(object sender, EventArgs e)
{
string url = @"img.png";
pictureBox1.Load(url);
SCIOX_bitmap a;
a.height = pictureBox1.Height;
a.width = pictureBox1.Width;
var source = new BitmapImage(new System.Uri(url));
int b = source.Format.BitsPerPixel;
a.color_depth = (4 * b) * b;
a.points = pictureBox1.Handle;
a = median(a, 8);      
}
public struct SCIOX_bitmap
{
public int width;
public int height;
public int color_depth;
public IntPtr points;
};

C++代码:

SCIOX_bitmap __stdcall median(SCIOX_bitmap image, int size)
{   
SCIOX_bitmap finMap;            
finMap.width = image.width;
finMap.height = image.height;
finMap.color_depth = image.color_depth;
finMap.points = new int[finMap.height*finMap.width];
int *valArr = new int[size*size]

for(int i=0; i<image.width; i++)
for(int j=0; j<image.height; j++)
{
for(int k=0,n=0; k<size; k++)
for(int l=0; l<size; l++,n++)
valArr[n] = image.points[((i-size/2+k+image.width)%image.width)*image.height + (j-size/2+l+image.height)%image.height];
**//AccessViolationException was unhandle**
mysort(valArr, size*size);  
if(size*size%2 == 1)
finMap.points[i*finMap.height + j] = valArr[size*size/2];
else                    
finMap.points[i*finMap.height + j] = (valArr[size*size/2-1] + valArr[size*size/2]) / 2;
}
return finMap;
}
struct SCIOX_bitmap{
int width;
int height;
int color_depth;
int* points;
};

有人帮我吗?


对不起,我忘了SCIOX_bitmap是结构体。SCIOX_bitmap也在c++代码中

public struct SCIOX_bitmap
{
public int width;
public int height;
public int color_depth;
public IntPtr points;
};

似乎您正在访问PictureBox类的Handle,就好像它是Image的句柄一样。这是不对的,Handle属性是控件的句柄。

如果你想获得图像本身的句柄,你需要将其转换为位图,然后使用GetHBitmap()

Bitmap bitmap = new Bitmap(pictureBox1.Image);
a.points = bitmap.GetHBitmap();

此外,我建议您研究C++代码的"三条规则",因为您将在每次调用median时泄漏为点缓冲区声明的内存。