问题
I have a simple function intReference
int intReference(int *intArray)
Where I am passing intArray by reference.
How do I set the interface file for SWIG such that it can do that?
Thanks,
回答1:
This is the pattern I think you want:
intReference.i
%module intReference
%{
extern int intReference(int intArray[]);
%}
%typemap(jtype) int intArray[] "int[]"
%typemap(jstype) int intArray[] "int[]"
%typemap(javain) int intArray[] "$javainput"
%typemap(jni) int intArray[] "jintArray"
%typemap(in) int intArray[] {
jboolean isCopy;
$1 = JCALL2(GetIntArrayElements, jenv, $input, &isCopy);
}
%typemap(freearg) int intArray[] {
JCALL3(ReleaseIntArrayElements, jenv, $input, $1, 0);
}
extern int intReference(int intArray[]);
intReference.c
int intReference(int intArray[]) {
intArray[0] = 42;
return 43;
}
Compiled with:
swig -java *.i
javac *.java
export JAVA_HOME=/usr/local/jdk1.8.0_60/
gcc -shared *.c -I "${JAVA_HOME}/include" -I "${JAVA_HOME}/include/linux" -o libintReference.so
Test Code(java)
System.loadLibrary("intReference");
int intArray[] = new int[1];
intReference.intReference(intArray);
System.out.println("intArray[0] = " + intArray[0]);
回答2:
There is an entire section about this in the SWIG documentation. Depending on your needs, you may be able to just use built-in typemaps and SWIG directives. For example,
%include "arrays_java.i"
%apply int[] {int *};
来源:https://stackoverflow.com/questions/33487089/swig-java-pass-by-reference-int