title: SWIG C function pointer and JAVA
body: <p>I have some code in C and one of the method has a function pointer as argument. I'm trying to use the C code in my Android app. </p>
  
  <p>I decided to use SWIG to do all the work in generating the java files I need. Everything works well with regular function (the one that doesn't have a function pointer as argument). </p>
  
  <p>But I'm not sure how I can pass my JAVA method as a callback to the C function. </p>
  
  <p>Here is an example : </p>
  
  <p>here is my multiply.h file</p>
  
  <pre><code>typedef int (*callback_t) (int a, int b, int c);
  
  int foo(callback_t callback);
  </code></pre>
  
  <p>here is my multiply.c file</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include "multiply.h"
  
  int foo(callback_t callback)
  {
      return callback(2, 4, 6);
  }
  </code></pre>
  
  <p>here is my interface file multiply-swig.i</p>
  
  <pre><code>%module example
   %{
   /* Includes the header in the wrapper code */
   #include "multiply.h"
   %}
  
   /* Parse the header file to generate wrappers */
   %include "multiply.h"
  </code></pre>
  
  <p>then I ran the following swig command to generate the java files I need</p>
  
  <pre><code>swig -java -package com.example.ndktest -o multiply-wrap.c mulitiply-swig.i 
  </code></pre>
  
  <p>and then swig generated the following files :</p>
  
  <p>example.java</p>
  
  <pre><code>package com.example.ndktest;
  
  public class example {
    public static int foo(SWIGTYPE_p_f_int_int_int__int callback) {
      return exampleJNI.foo(SWIGTYPE_p_f_int_int_int__int.getCPtr(callback));
    }
  
  }
  </code></pre>
  
  <p>exampleJNI.java</p>
  
  <pre><code>package com.example.ndktest;
  
  public class exampleJNI {
    public final static native int foo(long jarg1);
  }
  </code></pre>
  
  <p>SWIGTYPE_p_f_int_int_int__int.java</p>
  
  <pre><code>package com.example.ndktest;
  
  public class SWIGTYPE_p_f_int_int_int__int {
    private long swigCPtr;
  
    protected SWIGTYPE_p_f_int_int_int__int(long cPtr, boolean futureUse) {
      swigCPtr = cPtr;
    }
  
    protected SWIGTYPE_p_f_int_int_int__int() {
      swigCPtr = 0;
    }
  
    protected static long getCPtr(SWIGTYPE_p_f_int_int_int__int obj) {
      return (obj == null) ? 0 : obj.swigCPtr;
    }
  }
  </code></pre>
  
  <p>Now how can I call this <code>foo</code> method from my java code? The argument is of type <code>SWIGTYPE_p_f_int_int_int__int</code> ??? I don't understand how I can pass a JAVA method as callback to the C code ... I think I am definitely missing something here ....</p>
  
  <p>Any help is appreciated, thanks</p>