Thursday, April 15, 2010

C Function Pointer To Class Methods


















My current project at work involves me writing an application to sort data coming from a server and then repost it to the server in a shared memory buffer. The application is being developed in C++ but the server application was originally written in C. As a client of this server, I have to register a series of callback functions for various event transitions that occur on the server. The problem that I had was that I needed to pass a function pointer to an object method. However, you can't just pass a pointer to the method because you can't call an object method without an object to call it on. There are two solutions to this problem, the first is to pass a pointer to a static method. The second, is to set up a wrapper to the object method.

In the first method, you would do something like this
class A{
static void memberFunction();
};

int main(){
registerCallback(A::memberFunction);
}

This will work in most cases, however depending on your compiler it may not work. The reason is that to pass a completely standards compliant function pointer, you need to pass a pointer to a non-member function with C linkage (using an "extern C" call).

The second option is to use a wrapper function. Simply wrap the method call in a non-member function and then pass a pointer to that function. An example of this would be
class A{
void memberFunction();
};

A* pointerToCallbackObject;

void wrapperFunction{
pointerToCallbackObject->memberFunction();
}

int main(){
registerCallback(wrapperFunction);
}

No comments:

Post a Comment