Monday, June 15, 2009

Using JNI method in SWIG's input file

Sometimes we've to use JNI's built in methods in SWIG's input file. Though SWIG's proxy class can do everything possible for JNI,but I prefer to use JNI's method where SWIG gets complicated. For example, I have a byte Array in my java file.If I want to retrieve the array by pinning, we can use getArrayPrimitiveCritical(
) JNI method.Here I gonna give an example that will help you a lot about using JNI's built in method in SWIG.

Let the java file is Runner.java and the code is:


public class Runner {
static {
try {
System.loadLibrary("sample");
}
catch (UnsatisfiedLinkError e) {

System.err.println("Native code library failed to load.\n" + e);
System.exit(1);
}
}



public static void main(String argv[]) {
//declaration of the array
byte array[] = new byte [10000];
for (int i = 0; i <>
array[i] = (byte)((int)i%64);

//call the native method

sample.point_accessPinArray(array);
}
}


Now the input file can be like this(sample.i)

/* File : sample.i */

%module sample
%{
#include "ByteArray.h"
#include "/usr/lib/jvm/java-6-openjdk/include/jni.h"

JNIEXPORT void JNICALL Java_sampleJNI_point_1accessPinArray(JNIEnv *jenv, jclass jcls,jbyteArray array) {

int i;int size;
size = (*jenv)->GetArrayLength(jenv, array);
//pinning process is going to be started from here if your garbage collector supports //pinning.

jbyte* body = (*jenv)->GetPrimitiveArrayCritical(jenv, array, NULL);

(*jenv)->ReleasePrimitiveArrayCritical(jenv, array, body, 0);
}
%}
%native(point_accessPinArray) void *point_accessPinArray(jbyteArray array);



Commands to compile and run:

$swig -java sample.i
$gcc -c -fpic sample_wrap.cxx -I/usr/lib/jvm/java-6-openjdk/include/ -I/usr/lib/jvm/java-6-openjdk/include/linux/
$gcc -shared sample_wrap.o -o libexample.so
$export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
$javac Runner.java
$java Runner

No comments: