I’m having issues passing in an appropriate Java data type for the fetchByType C function’s length parameter from my Java implementation (both below). On the C side, the *length parameter is a pointer to a length variable (output) to indicate the size of the data to be returned from the fetchByType C function. I’ve tried to use the SWIG %apply int32_t { int32_t * } and pass an int initialized at 0 from my Java implementation but that fails. I’ve also tried passing in a SWIGTYPE_p_int as shown below, but that also doesn’t work. I don’t have an exception unfortunately as this just crashes.
C Function:
void * fetchByType(struct row_t *result_row, type_t attribute, int32_t *length);
Generated Java from SWIG:
public static String fetchByType(SWIGTYPE_p_result_row_t result_row, type_t attribute, SWIGTYPE_p_int length)
Java Implementation:
SWIGTYPE_p_int length = new SWIGTYPE_p_int();
fetchByType(result_row, attribute, length)
The problem here is that you need to pass something that can be changed into the C function. That means you can’t use a primitive in Java (e.g.
int) since Java always passes primitives by value.There’s only really one sensible way you can work around this. SWIG in fact already provides a few typemap we can use that passes this as an array instead. Arrays in Java are “objects” and so
int[]is passed by reference even thoughintisn’t. A simplified example based on the function you show above, first test.h:And a module file, test.i:
This just makes sure we apply the appropriate
*OUTPUTtypemap. (stdint.i maps this onto a real C primitive for you). I tested with:It’s a bit of a hack1, but it’s usable. Another approach might be to use a
java.lang.Integer, which also represents anintand is a properObjectso gets passed by reference. The problem there is thatjava.lange.Integeris immutable however and I’m not actually sure enough how that works on the JNI side to provide an example of this.1 Other languages SWIG supports alter the return type for some typemaps and return a tuple or similar for OUTPUT arguments, but that’s not really feasible with Java.