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

If you are looking for more JNI samples, take a look here: http://jnicookbook.owsiak.org

Comments (3)

anonymousApril 3rd, 2018 at 12:18 pm

Good Example

anonymousApril 3rd, 2018 at 8:57 pm

Thanks!

Smithk234June 21st, 2018 at 1:50 pm

A big thank you for your article.Really thank you! Cool.