Simple JNI Example

Make a native method in java and call it.

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

public native int multiply(int a, int b);

public static void main(String[] args) {

	GetPhotoData getPhotoData = new GetPhotoData();

	int a = 8;
	int b = 6;

	int c = getPhotoData.multiply(a, b);
	System.out.println(c);
}

Compile it with
javac Filename.java

Now run the following command to make the header(.h) file
javah -jni Filename

It will generate a header file with proper name and will have native method signature in it.

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

#ifndef _Included_com_financial_inclusive_jni_GetPhotoData
#define _Included_com_financial_inclusive_jni_GetPhotoData
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_financial_inclusive_jni_GetPhotoData
 * Method:    multiply
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_com_financial_inclusive_jni_GetPhotoData_multiply
  (JNIEnv *, jobject, jint, jint);

#ifdef __cplusplus
}
#endif
#endif

Now as the header file is created and the method signature of the native method to be implemented is there, make a C file which implements the method. Include the header file so it can find it.

#include "com_financial_inclusive_jni_GetPhotoData.h"

JNIEXPORT jint JNICALL Java_com_financial_inclusive_jni_GetPhotoData_multiply
  (JNIEnv *env, jobject thisobject, jint ja, jint jb){
	return ja*jb;
}

I did it on windows. So I had to make a dll file and keep it under C:/WINDOWS/System32 which is added to my %path% system variable.

I’ve used Borland compiler to generate the dll by running

D:\Borland\BCC55\Bin>bcc32 -WD d:\workspace\FinancialIncl\src\multiply.c

When first time compiled it will throw an error and quite.

Here you see that the C method created has two more extra arguments than we passed. The first one is the pointer to JVM environment and the second one is the reference object to the class. In our case we do not use those variables in our C implementation. So the compiler just gives warning about it and exits. We have to suppress these warnings to create the dll.

D:\Borland\BCC55\Bin>bcc32 -WD -w-par d:\workspace\FinancialIncl\src\multiply.c

Here is a nice reference from where I got all the resources.
And for Borland command options, please refer this.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: