Search code examples
c#openglopentk

C# Attempted to read or write protected memory. OpenGL/OpenTK libraries


I'm trying to execute following code:

static void Main(string[] args)
    {
        int Width = 512, Height = 512; //window size
        var CubeSize = 200; // square size
        int left, right, top, bottom;
        left = (Width - CubeSize) / 2;
        right = left + CubeSize;
        bottom = (Height - CubeSize) / 2;
        top = bottom + CubeSize;
        GL.ClearColor(0, 0, 0, 1);
        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        GL.Color3(255, 0, 0);
        GL.Begin(BeginMode.Quads);
        GL.Vertex2(left, bottom);
        GL.Vertex2(left, top); 
        GL.Vertex2(right, top);
        GL.Vertex2(right, bottom);
        GL.End();

    }

In line GL.ClearColor it throws an error:

Attempted to read or write protected memory

Need some help.


Solution

  • To use most of the GL methods, you need to be on the GL thread. The best way to tell if you are on a GL thread is if any of the overriden GameWindow methods are called by the running GameWindow. If you want to change the GL thread, you need to make a new window on a different thread and then use window.MakeCurrent().

    If you use it anywhere different ( for example, if you dispose of a texture from a GC finalizer ), you might get that exception.