加载纹理时,OpenTK.dll中出现“System.AccessViolationException”

时间:2016-12-13 01:14:45

标签: c# opengl 3d game-engine opentk

所以我目前正在使用OpenTK在C#中使用3D OpenGL游戏引擎,但是当我去添加纹理加载时我遇到了一个问题

我收到此错误

An unhandled exception of type 'System.AccessViolationException' occurred in OpenTK.dll Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

我不是百分之百确定为什么我会收到“内存损坏”错误,我不应该,我之前使用过这段代码而且我现在才收到此错误。

这是我的代码:

`

    public static int UploadTexture(string pathname)
    {
        // Create a new OpenGL texture object
        int id = GL.GenTexture(); //THIS IS THE LINE VISUAL STUDIO POINTS OUT WHEN I GET THE ERROR

        // Select the new texture
        GL.BindTexture(TextureTarget.Texture2D, id);

        // Load the image
        Bitmap bmp = new Bitmap(pathname);

        // Lock image data to allow direct access
        BitmapData bmp_data = bmp.LockBits(
                new Rectangle(0, 0, bmp.Width, bmp.Height),
                System.Drawing.Imaging.ImageLockMode.ReadOnly,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        // Import the image data into the OpenGL texture
        GL.TexImage2D(TextureTarget.Texture2D,
                      0,
                      PixelInternalFormat.Rgba,
                      bmp_data.Width,
                      bmp_data.Height,
                      0,
                      OpenTK.Graphics.OpenGL.PixelFormat.Bgra,
                      OpenTK.Graphics.OpenGL.PixelType.UnsignedByte,
                      bmp_data.Scan0);

        // Unlock the image data
        bmp.UnlockBits(bmp_data);

        // Configure minification and magnification filters
        GL.TexParameter(TextureTarget.Texture2D,
                TextureParameterName.TextureMinFilter,
                (int)TextureMinFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D,
                TextureParameterName.TextureMagFilter,
                (int)TextureMagFilter.Linear);

        // Return the OpenGL object ID for use
        return id;
    }

`

1 个答案:

答案 0 :(得分:0)

像你这样的问题通常与越界内存访问有关。虽然C#和CLI提供了一个内存安全执行环境,但OpenGL本身是一个不安全的API,除非你在调用OpenGL之前使用一个执行某些验证的包装器,否则就会发生这种情况。

那么最有可能造成麻烦的原因是什么?为什么OpenGL访问内存超出范围?一个字:对齐!

默认情况下,OpenGL假定图像行与4字节边界对齐。假设您的实际图像数据行与1字节边界对齐,您的图像宽度是3的倍数,但是2和4都不是OpenGL将读取图像高度超过图像实际占用的内存区域3个字节。

解决方案很简单:告诉OpenGL图像数据的对齐方式。对于BMP部分,它恰好是1字节对齐。在glTexImage2D调用之前添加:

GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1);
相关问题