Sunday, May 12, 2013

Get Started with JNI

Step 1: Create a Java test file JNITest.java
public class JNITest {
    public native void printString();

    static {
        System.loadLibrary("printstr");
    }   

    public void print() {
        printString();
    }   

    public static void main(String args[]) {
        (new JNITest()).print();
    }   
}
Step 2: Compile the Java file and generate a header file JNITest.h
$javac JNITest.java
$javah -jni JNITest
Step 3: Create a C test file printstr.c
#include <stdio.h>
#include <jni.h>
#include "JNITest.h"

JNIEXPORT void JNICALL Java_JNITest_printString (JNIEnv* env, jobject obj)
{
    printf("Hello, World!\n");
}
Step 4: Compile C file to produce the native lib "libprintstr.jnilib"
$gcc -dynamiclib -o libprintstr.jnilib -I/System/Library/Frameworks/JavaVM.framework/Headers printstr.c -framework JavaVM
Step 5: Run the Java test, which would show "Hello World!"
$java JNITest

No comments:

Post a Comment