I was working on a project with GLFW.NET and OpenGL.NET when i encountered this error
Glfw.SetMouseButtonCallback(glfwWindow, MouseListener.mousePosCallback);
here is the MouseListener.mousePosCallback code:
public static void mouseButtonCallback(GLFW.Window window, int button, GLFW.InputState action, int mods) {
if (action == GLFW.InputState.Press) {
if (button < get().mouseButtonPressed.Length) {
get().mouseButtonPressed[button] = true;
}
} else if (action == GLFW.InputState.Release) {
if (button < get().mouseButtonPressed.Length) {
get().mouseButtonPressed[button] = false;
get().isDragging = false;
}
}
}
I don't understand why is this happening because when i use other functions like glfw.SetCursorPositionCallback everything works how it's expected. Is this some kind of bug or am i missing something ?
Glfw.SetMouseButtonCallback(glfwWindow, MouseListener.mousePosCallback);
C# tries hard to make code readable by hiding boilerplate like object creation, but that line of code actually means:
Glfw.SetMouseButtonCallback(glfwWindow, new SetMouseButtonCallback(MouseListener.mousePosCallback));
So what you're sending to that native function (glfwSetMouseButtonCallback
) is a function pointer through your newly created delegate that holds a handle to your static method, and the native function returns immediately.
Once the function returns, there's nothing rooting your delegate, and so whenever your memory pressure increases enough and your GC kicks in to start collecting left-over garbage, it will collect your delegate and the function handle within, so when the native glfw tries to call your handler, your delegate is gone, so you get an exception.
To fix this, simply root your delegate as a field in your class or something.