How do I have a CALLBACK function in a Class, so that it can access the member variables? I'm trying to write a DirectInput class, but the 'Enum' Callback functions will require access to the classes' variables.
If you need more info, please ask.
Printable View
How do I have a CALLBACK function in a Class, so that it can access the member variables? I'm trying to write a DirectInput class, but the 'Enum' Callback functions will require access to the classes' variables.
If you need more info, please ask.
The callback would have to have some way of looking up the current object and then call a method on that (I'm pretty sure this is how MFC does it or something similar).
Like if there is a User defined parameter for the callback you could set that to the address of the current object.
Other than that there really isn't anything you can do.
Class methods (except static methods) use a calling convention all by itself (that's how the this pointer gets passed in). The CALLBACK macro is defined as __stdcall, which is another calling convention. And last time I checked one function cannot have two calling conventions.
I'm not familiar with what a DirectInput class is, so I can't help you out... until I have a little more information.
Actually class methods use an extended calling convention: thiscall can extend stdcall, fastcall and cdecl. But no extended version can be used instead of a non-extended version.
Every callback in windows allows you to pass a user-defined parameter, usually of type LPARAM or LPVOID (void *). You can simply pass the this pointer there.
I'm gonna need a little more help with this I think.
This is the line which calls the Callback function:
m_pDirectInput->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback, this, DIEDFL_ATTACHEDONLY)))
The second parameter is the Callback function in question:
int CALLBACK EnumJoysticksCallback(const DIDEVICEINSTANCE* pdidInstance, VOID* pContext) {
....
}
[This passes a this pointer into the Callback with the second parameter]
How do I then use pContext as a 'this' pointer?
Pass the stub as the callback function.Code:// class declaration:
static int CALLBACK EnumJoysticksCallbackStub(const DIDEVICEINSTANCE* pdidInstance, VOID* pContext);
int EnumJoysticksCallback(const DIDEVICEINSTANCE* pdidInstance);
// Implementation file
int CALLBACK CYourClass::EnumJoysticksCallbackStub(const DIDEVICEINSTANCE* pdidInstance, VOID* pContext)
{
return (reinterpret_cast<CYourClass*>(pContext))->
EnumJoysticksCallback(pdidInstance);
}
int CYourClass::EnumJoysticksCallback(const DIDEVICEINSTANCE* pdidInstance)
{
....
}
It's working! Yey!
It was the "reinterpret_cast<CDirectInput*>(pContext) " I missed out...