【问题标题】:Attempted to read or write protected memory. This is often an indication that other memory is corrupt. in C++ Dll尝试读取或写入受保护的内存。这通常表明其他内存已损坏。在 C++ DLL 中
【发布时间】:2014-03-22 18:14:29
【问题描述】:

我的代码有问题。 当我编译程序时,它会写“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;
    };

【问题讨论】:

  • 什么是 SCIOX_Bitmap?当涉及到存储在其中的动态内存时,您是否遵守三法则?

标签: c# c++ dll


【解决方案1】:

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

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

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

此外,我建议您查看 C++ 代码的 Rule of Three,因为您将在每次调用 median 时泄漏为点缓冲区声明的内存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-23
    相关资源
    最近更新 更多