Wrap a C ++ function pointer callback with SWIG

I am working on porting the C ++ library used in desktop and iOS applications to Android. I use SWIG to generate JNI code, and I'm about 90% of the way to where I need it. The only problem I ran into was wrap the callback functions from the C ++ library.

In my main device class, I have the following:

class Device { public: void set_receive_callback(ReceiveFunctonPointer func, void *userdata); }; 

The callback function and structure data have the following signature:

 // enum wrapped by SWIG enum CommandType { ... }; // enum wrapped by SWIG enum ValueFormat { ... }; // Value map wrapped by SWIG typedef std::map<int, std::string> ValueMap; // struct to be passed back. Already wrapped into Java class by SWiG struct DeviceReceive { void *userdata; CommandType command; std::string messageId; std::string value; ValueFormat format; ValueMap value_map; Device *device; }; // the callback function signature typedef void (*ReceiveCallback)(DeviceReceive data); 

From what I read, I will need to create some kind of DeviceCallback interface in Java that will be used. It should be something simple:

 package my.sdk; import my.sdk.DeviceReceive; public interface DeviceCallback { void handleCallback(DeviceReceive data); } 

My question is: using SWIG, how do I get a callback, create a java DeviceReceive class from the C ++ DeviceReceive , and then call the Java callback handler. Note that the callback also occurs in a random background thread created by the C ++ library.

+4
source share

All Articles