Monday, September 22, 2014

JNI tutorial for Mac OSx 10.9.4


JNI info

1. Install Eclipse IDE
2. Create new project
3. New class Hello.java (copy and paste code below)

public class Hello {
    public native int add(int a, int b);
    private native void sayHello();
   
   
    public static void main(String [] args) 
    {
    System.out.println(new Hello().add(34,50));
   
    new Hello().sayHello();
    }
    static {
    System.loadLibrary("hello");
    }

}

4. Open terminal. Go to file /dir. Enter below commands: 
    $javac Hello.java (compiles)
    $javah -jni -classpath . Hello

The above command generates your .h headers files from the Java.

5. Now create file "hello.c" copy and paste code below:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Hello */

#ifndef _Included_Hello
#define _Included_Hello
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     Hello
 * Method:    add
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_Hello_add
  (JNIEnv *, jobject, jint, jint);

/*
 * Class:     Hello
 * Method:    sayHello
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_Hello_sayHello
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

6. Now enter following commands

  $gcc -dynamiclib hello.c -I/System/Library/Frameworks/JavaVM.framework/Headers -o libhello.dylib

  $cp libhello.dylib /Library/Java//Extensions

  $java -cp . Hello

Output: 
84
Hello World!

Commands used (img):











No comments:

Post a Comment