C# 试图读取或写入受保护的内存。 OpenGL/OpenTK 个图书馆

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

我正在尝试执行以下代码:

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();

    }

在行 GL.ClearColor 中抛出一个错误:

Attempted to read or write protected memory

需要一些帮助。

要使用大部分 GL 方法,您需要在 GL 线程上。判断您是否在 GL 线程上的最佳方法是 运行 GameWindow 是否调用了任何覆盖的 GameWindow 方法。如果你想改变GL线程,你需要在不同的线程上创建一个新的window然后使用window.MakeCurrent().

如果您在任何不同的地方使用它(例如,如果您从 GC 终结器中处理纹理),您可能会遇到该异常。