How do I fix the System.AccessViolationException in my OpenTK Code (C#)?

2 weeks ago 24
ARTICLE AD BOX

I am trying to make a square from triangles using indices and vertices, but when I run the code it says this: System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

Here is my code:

using OpenTK.Graphics.OpenGL4; using OpenTK.Windowing.Common; using OpenTK.Windowing.Desktop; using OpenTK.Windowing.GraphicsLibraryFramework; namespace ByteCraftMCknockoff { public class BCWindow : GameWindow { private readonly float[] vertices = { 0.5f, 0.5f, 0.0f, //bottom left 0.5f, -0.5f, 0.0f, //bottom right -0.5f, -0.5f, 0.0f, //top left -0.5f, 0.5f, 0.0f //top right }; private readonly uint[] indices = { 0, 1, 3, 1, 2, 3 }; private Shader shader; private int vbo; private int ebo; private int vao; public BCWindow(int width, int height, string title) : base(GameWindowSettings.Default, new NativeWindowSettings() { ClientSize = (width, height), Title = title }) { } protected override void OnLoad() { base.OnLoad(); var sky = OpenTK.Mathematics.Color4.CornflowerBlue; GL.ClearColor(sky); shader = new Shader("shader.vert", "shader.frag"); vbo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, vbo); GL.BufferData(BufferTarget.ArrayBuffer, vertices.Length * sizeof(float), vertices, BufferUsageHint.StaticDraw); ebo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ElementArrayBuffer, ebo); GL.BufferData(BufferTarget.ElementArrayBuffer, indices.Length * sizeof(uint), indices, BufferUsageHint.StaticDraw); vao = GL.GenVertexArray(); GL.BindVertexArray(vao); GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 3 * sizeof(float), 0); GL.EnableVertexAttribArray(0); shader.Use(); } protected override void OnUpdateFrame(FrameEventArgs e) { base.OnUpdateFrame(e); if (KeyboardState.IsKeyDown(Keys.Escape)) { this.Close(); } } protected override void OnFramebufferResize(FramebufferResizeEventArgs e) { base.OnFramebufferResize(e); GL.Viewport(0, 0, e.Width, e.Height); } protected override void OnRenderFrame(FrameEventArgs e) { base.OnRenderFrame(e); GL.Clear(ClearBufferMask.ColorBufferBit); shader.Use(); GL.BindVertexArray(vao); GL.DrawElements(PrimitiveType.Triangles, indices.Length, DrawElementsType.UnsignedInt, 0); SwapBuffers(); } public void DrawCube() { shader.Use(); GL.BindVertexArray(vao); GL.DrawElements(PrimitiveType.Triangles, indices.Length, DrawElementsType.UnsignedInt, 3); } protected override void OnUnload() { GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.BindVertexArray(0); GL.UseProgram(0); GL.DeleteBuffer(vbo); GL.DeleteVertexArray(vao); GL.DeleteProgram(shader.Handle); base.OnUnload(); } } }

It says it specifically on this line:

GL.DrawElements(PrimitiveType.Triangles, indices.Length, DrawElementsType.UnsignedInt, 0);

How do I make that error go away so I can see if I made a square or not?

Read Entire Article