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

public class HelloJni{

	private native void sayHello();

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


then compile this code. Run this on your terminal


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

it will create HelloJni.h

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

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

#ifdef __cplusplus

3. Create the implementation file


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


using namespace std;

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

4. Now create the dynamic lib of the cpp's code. I used Fish shell, firstly I set up these variables
set JNIH  /Applications/
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++!


No comments:

Post a Comment

Comment is caring :)