SWIG - Java - Pass by reference int

余生长醉 提交于 2019-12-13 06:08:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!