narain narain - 1 year ago 79
C++ Question

Access properties of object from static method

I am programming against an external library which requires a static callback function. I declared my callback as static but then i loose access to the object properties i want to modify with this callback.

static void selCallback(void* userData, SoPath* selPath);

void MyClass::selCallback(void* userData, SoPath* selPath) {
classProperty = 3;

Is there a way how can create a static callback while being able to access my current objects properties? The library i use is the openInventor library. The callback wiring up is done with the following code:

SoSelection *selNode = new SoSelection;

Answer Source

The addSelectionCallback method has an optional parameter for userData pointer. There you should send the object instance, which you will receive then in your callback.

Inside the method, you can typecast to the correct object type and do the actual work with the object instance.

For example:

void MyClass::selCallback(void* userData, SoPath* selPath) {
    static_cast<MyClass *>(userData)->classProperty = 3;

MyClass myInstance;
selNode->addSelectionCallback(MyClass::selCallback, &myInstance);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download