This example returns the maximum of an int array.
JNIEXPORT jint JNICALL Java_JavaHowTo_max(JNIEnv * env, jclass obj, jintArray arr) {
int i;
jsize len = env->GetArrayLength(arr, max = -1;
jint *body = env->GetIntArrayElements(arr, 0);
for (max = body[0], i=1; i < len; i++)
if (max < body[i]) max = body[i];
env->ReleaseIntArrayElements(arr, body, 0);
return max;
} |
class JavaHowTo {
public static native int max(int [] t);
static {
System.loadLibrary("javahowto");
}
} |
class JNIJavaHowTo {
public static void main(String[] args) {
int [] myArray = {4, 7, 5, 9, 2, 0, 1};
System.out.println(JavaHowTo.max(myArray));
}
}
|
This following how-to is currently broken...
Without passing the array directly to the JNI function,
it's possible to fetch directly from the class the array.
JNIEXPORT jint JNICALL Java_JavaHowTo_printArray(JNIEnv * env, jclass obj) {
jfieldID fid;
jobject jtab;
jsize len;
int i;
jclass cls = env->GetObjectClass(obj);
fid = env->GetFieldID(cls, "myArray", "[I");
if (fid == 0) return;
jtab = env->GetObjectField(obj, fid);
tab = env->GetIntArrayElements(jtab, 0);
len = env->GetArrayLength(jtab);
printf("int [] : [");
for (i = 0; i < len ; i++) printf("%d ", tab[i]);
printf("]\n");
}
|
Written and compiled by Réal Gagnon ©1998-2005
[ home ]