Friday, December 5, 2014


what you have, you will not want
what you want, you will not see
what you see, you will not appreciate
what you appreciate, you will not have

what you have, you will appreciate
what you appreciate, you will see
what you see, you will want
what you want, you will have

Friday, June 10, 2011

Java Native Interface

The JNI API allows your Java application to talk to other applications written in C/C++. So today I'll show an example on how to get your Java class talk to a C program. I'll briefly describe the steps below.

First, create a Java file (I'll name our class TestJNI).
class TestJNI {

public static void main(final String[] args) {
TestJNI test = new TestJNI();

public native void printText();
Compile the source above to create a class file.
> javac
This will generate the class file TestJNI.class. The method you need to take note here is the public native void printText() method. This is the method that we are calling in the program written in C. The native modifier tells the compiler that when this method is invoked call the C program.

Once you have the class file, the next step is to generate the C/C++ header file with the javah command. You can find the javah command in your JDK bin directory.
> javahTestJNI
A new file will be generated. We now have three files,
  • TestJNI.class
  • TestJNI.h
In this example, I am using Microsoft Visual C++ 2010 Express. You can get it off Microsoft site and you need to obtain the registration key to activate the license. Once you got it running, create a new empty Win32 Project project.

Include the JNI header files into the project. Right click on "Project Name" > Properties > Configuration Properties > VC++ Directories > Include Directories. You need to include all the directories for the JNI header files, which is located at ${JAVA_HOME}/include and ${JAVA_HOME}/include/win32. Include also the directory where your TestJNI.h file is located in this step.

Next, add TestJNI.h file to your project. Create a .cpp file. In this example, I am naming it Entry.cpp. Open TestJNI.h with any editor. Copy the bolded section to Entry.cpp.
/* DO NOT EDIT THIS FILE - it is machine generated */
/* Header for class TestJNI */

#ifndef _Included_TestJNI
#define _Included_TestJNI
#ifdef __cplusplus
extern "C" {
* Class: TestJNI
* Method: printText
* Signature: ()V
JNIEXPORT void JNICALL Java_TestJNI_printText
(JNIEnv *, jobject);

#ifdef __cplusplus
Your Entry.cpp should have the following.
#include "TestJNI.h"

JNIEXPORT void JNICALL Java_TestJNI_printText(JNIEnv *, jobject) {
printf("HELLO WORLD");
Build the solution and get the .dll file generated. The name of the dll file is your project name. You should be able to find it somewhere off the debug folder of your project. Next, we need to include this in your Java program using the System.load command.

Your Java application should print HELLO WORLD. Hope that helps.

Share it