PDA

Click to See Complete Forum and Search --> : CALLBACK functions in Classes


Barguast
Dec 19th, 2002, 01:35 PM
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.

amac
Dec 19th, 2002, 02:48 PM
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.

CornedBee
Dec 21st, 2002, 08:09 AM
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.

Barguast
Dec 28th, 2002, 09:30 AM
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?

CornedBee
Dec 29th, 2002, 04:09 AM
// 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)
{
....
}


Pass the stub as the callback function.

Barguast
Dec 29th, 2002, 07:37 AM
It's working! Yey!

It was the "reinterpret_cast<CDirectInput*>(pContext) " I missed out...