Buy Me A Coffee!

GoPay

Friday, October 31, 2014

Using JNI on OSX

JNI is the way Java using the other programming language. JNI is cool because it's executed a lot faster.

There's a tutorial from NTU, but it's using Windows as it's platform. Sadly I am using *nix. *sob*. But sad no more, I've managed how to use it.
Oh yeah, this tutorial is based on the NTU's tutorial and Kemp's tutorial

1. Create the Java code. For simplicity on this tutorial I named it as HelloJni.java

public class HelloJni{
	
	static{
		System.loadLibrary("HelloJni");
	}

	private native void sayHello();

	public static void main(String args[]){
		new HelloJni().sayHello();
	}

}

then compile this code. Run this on your terminal

javac HelloJni.java

2. Create the header file of C/C++
javah HelloJni

it will create HelloJni.h

/* DO NOT EDIT THIS FILE - it is machine generated */
#include 
/* Header for class HelloJni */

#ifndef _Included_HelloJni
#define _Included_HelloJni
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloJni
 * Method:    sayHello
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_HelloJni_sayHello
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif


3. Create the implementation file

HelloJniImpl.h
#ifndef _HELLO_JNI_IMPL_H
#define _HELLO_JNI_IMPL_H

#ifdef __cplusplus
		extern "C" {
#endif
		void sayHello();
#ifdef __cplusplus
	}
#endif

#endif


HelloJniImpl.cpp
using namespace std;

void sayHello () {
	cout << "Hello world from C++!" << endl;
	return;
}


4. Now create the dynamic lib of the cpp's code. I used Fish shell, firstly I set up these variables
set JNIH  /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/System/Library/Frameworks/JavaVM.framework/Versions/A/Headers/
set JDKH /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home/lib/

Then run this two line

g++ -I"$JDKH" -I"$JNIH" -shared -o HelloJni.o HelloJni.cpp HelloJniImpl.cpp 
g++ -dynamiclib -o libhellojni.jnilib HelloJni.o

5. Run your java app
java HelloJni

the result of the program is would be like this:

Hello world from C++!


Enjoy!

No comments:

Post a Comment

Comment is caring :)