Great question!
You're correct — to use a class method like keyboard_input() as a GLFW key callback, you can't directly pass self via glfw.set_key_callback() because the callback function signature is fixed to:
def key_callback(window, key, scancode, action, mods):
...
But there is a clean and supported pattern for associating instance methods with GLFW callbacks:
✅ Use glfw.set_window_user_pointer(window, self) and retrieve it inside the callback
🔁 Step-by-step Solution
🔸 Step 1: Attach your instance (self) to the window using GLFW's user pointer
When you create your window:
self.window = glfw.create_window(width, height, "My App", None, None)
glfw.make_context_current(self.window)
glfw.set_window_user_pointer(self.window, self)
Now, the window “carries” a reference to your class instance.
🔸 Step 2: Register a wrapper callback
Create a standalone function (outside the class) that will fetch self and call your method:
def key_callback(window, key, scancode, action, mods):
# Retrieve the class instance from the window's user pointer
obj = glfw.get_window_user_pointer(window)
if obj:
obj.keyboard_input(key, scancode, action, mods)
Register it like this:
glfw.set_key_callback(self.window, key_callback)
🔸 Step 3: Modify your class method to not expect self.window passed in
Since self.window is already stored in the object, your existing method:
def keyboard_input(self, key, scancode, action, mods):
...
Can remain mostly unchanged – you're just indirectly passing it via the GLFW user pointer.
💡 Bonus tip: Use action == glfw.PRESS inside the method as the GLFW key callback gives you press/release/repeat info.
✅ Summary
| Task | Use |
|---|
| Store instance | glfw.set_window_user_pointer(window, self) |
| Fetch it in callback | |