Simple JNI – passing array from Java to C

Create these files:

/* Simple.h */
#include "jni.h"
JNIEXPORT void JNICALL Java_Simple_passArray
  (JNIEnv *, jobject, jintArray);
/* Simple.c */
#include <stdio.h>
#include <stdlib.h>
#include "Simple.h"
#include "jni.h"

JNIEXPORT void JNICALL Java_Simple_passArray
  (JNIEnv *env, jobject obj, jintArray ptr) {

  int i;
  printf("Hello from JNI\n");
  jsize len = (*env)->GetArrayLength(env, ptr);
  jint *body = (*env)->GetIntArrayElements(env, ptr, 0);
  for (i=0; i < len; i++)
    printf("Hello from JNI - element: %d\n", body[i]);
  (*env)->ReleaseIntArrayElements(env, ptr, body, 0);
}
/* Simple.java */
class Simple {
  public native void passArray(int [] array);
  static {
    System.loadLibrary("Simple");
  }
}
/* Main.java */
public class Main {
  public static void main(String[] args) {
    System.out.println("library: " + System.getProperty("java.library.path"));
    Simple simple = new Simple();
    System.out.println("Passing array to C");
    int [] array = {1, 2, 3, 4, 5};
    simple.passArray(array);
  }
}

Execute following commands:

export JAVA_HOME=/wherever_your_java_path_is/
$JAVA_HOME/bin/javac *.java
$JAVA_HOME/bin/javah -jni Simple
cc -g -shared -fpic -I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux \
  Simple.c -o libSimple.so
export LD_LIBRARY_PATH=`pwd`:$LD_LIBRARY_PATH
$JAVA_HOME/bin/java Main

— MAC OS X —

cc -g -shared -fpic -I/Library/Java/Home/include Simple.c -o libSimple.dylib

Leave a comment

Your comment