title: Wrap a C++ Function Pointer Callback with SWIG
body: <p>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.</p>
  
  <p>In my main Device class, I have the following:</p>
  
  <pre><code>class Device
  {
  public:
      void set_receive_callback(ReceiveFunctonPointer func, void *userdata);
  };
  </code></pre>
  
  <p>The callback function and struct data have the following signature:</p>
  
  <pre><code>// enum wrapped by SWIG
  enum CommandType {
      ...
  };
  
  // enum wrapped by SWIG
  enum ValueFormat {
      ...
  };
  
  // Value map wrapped by SWIG
  typedef std::map&lt;int, std::string&gt; 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);
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>package my.sdk;
  import my.sdk.DeviceReceive;
  
  public interface DeviceCallback {
      void handleCallback(DeviceReceive data);
  }
  </code></pre>
  
  <p>My question is, using SWIG, how do I get from the callback, create the java <code>DeviceReceive</code> class from the C++ <code>DeviceReceive</code> struct, then call the Java callback handler.  Note that the callback also occurs on a random background thread created by the C++ library.</p>