I have a bit complicated class.
In this class I have a reference:
Private:
IEtApiPtr _pIEtApi;
IEtApiPtr is defined in a .tlh file:
_COM_SMARTPTR_TYPEDEF(IEtApi, __uuidof(IEtApi));
IEtApiPtr has a void named "SetRawDataCB"
virtual HRESULT __stdcall SetRawDataCB (
/*[in]*/ long address,
/*[in]*/ long userData,
/*[out,retval]*/ enum ApiError * pRetVal ) = 0;
I have defined a callback function in the class:
void CETAPI::RawDataCB(RawData& r, void* userData)
{
//do something
}
Now I want to install a callback using
_pIEtApi->SetRawDataCB((long)(__int64)(&RawDataCB),0,&result);
... the compiler tells me "Error C2276: Invalid operation for expression of a bound member function".
What did I do wrong here?
This doesn't work because RawDataCB
is a member function not a global function. You can declare RawDataCB
as a static function in the class as follows and this will work. However you will no longer have access to the this
pointer (i.e. no member variables) unless you add it as a parameter to RawDataCB
and perhaps make RawDataCB
a friend to gain access to private data of the class as a member function would have. This can be done by updating the function declaration as follows:
class CETAPI {
static void RawDataCB(RawData& r, void* userData);
};
Alternatively, you can pass a pointer to RawDataCB
as a member function pointer rather than a function pointer. Member function pointers can be manipulated as follows, so you will just pass an object of type RawDataCBType
to SetRawDataCB
.
typedef void (CETAPI::*RawDataCBType)(RawData&, void*); // typedef the member function pointer type
RawDataCBType pmf = &CETAPI::RawDataCB; // create and initialize a pointer to the member function
pCETAPIObject->*pmf(r, userData); // call the member function on an object of type CETAPI
Here is a good article that talks about member pointers.