4

I'm working on porting a C++ library used in desktop and iOS applications to Android. I'm using SWIG to create the JNI code and I'm about 90% of the way to where I need to be. The only issue I have left is wrapping 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 struct 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've read, I'll need to create some sort of DeviceCallback interface in Java to be used. That should be something simple like:

package my.sdk;
import my.sdk.DeviceReceive;

public interface DeviceCallback {
    void handleCallback(DeviceReceive data);
}

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

Grant Limberg
  • 20,913
  • 11
  • 63
  • 84
  • Do any of these answers on: [directors](http://stackoverflow.com/a/11158998/168175), [callbacks](http://stackoverflow.com/a/12251183/168175) or [interfaces](http://stackoverflow.com/a/8246375/168175) cover it? If not I can write a more specific answer. You should be able to do all this with directors though. – Flexo Dec 23 '12 at 12:04
  • Or alternatively, if you would like an answer that uses [JavaCPP](http://code.google.com/p/javacpp/), let me know! – Samuel Audet Jan 05 '13 at 05:56
  • I think this is the answer: http://stackoverflow.com/questions/13476429/how-to-pass-java-function-pointer-to-c-native-code – bme Jan 06 '13 at 09:24

0 Answers0