1

概括:

我用汇编程序编写了一个小型游戏引擎,并通过 DllImport 在我的 C# 项目的一个类中使用我的引擎 DLL 中的导出函数。到目前为止一切正常,但是在执行 LoadTexture 函数时我不断收到AccessViolationException 。

它旨在通过 .NET Frameworks Bitmap 类加载纹理,并将第一个像素数据 (mybitmap.Scan0) 的地址传递给我的本机 DLL,然后由它渲染我的纹理。但是,一旦本机代码尝试从此内存地址访问数据,我就会得到AccessViolationException

这就是我的这个函数的 DllImport 代码的样子:

[System.Runtime.InteropServices.DllImportAttribute("engine.dll", 
    CharSet = CharSet.Ansi, 
    CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall, 
    ExactSpelling = true), 
    System.Security.SuppressUnmanagedCodeSecurity
]
private static extern void LoadTexture(int width, int height, IntPtr handle);

这是调用我的本机函数的 C# 代码:

public static void LoadTexture(string file)
{
    Bitmap bitmap = new Bitmap(file);

    BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, 
    bitmap.Width, bitmap.Height),
    ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    LoadTexture(data.Width, data.Height, data.Scan0);
}

问题:

  • 我的 DllImport 语句中可能有错误还是看起来没问题?

  • 还有什么可能是这个问题的原因?

如果您需要更多可能有助于解决我的问题的信息,请随时在评论中问我。

4

1 回答 1

2

您是否已将纹理位图锁定到内存中?您需要在使用Bitmap.LockBits()指针之前使用。

请参阅http://msdn.microsoft.com/en-us/library/5ey6h79d.aspx

于 2012-11-09T02:47:41.437 回答