Java provides a simple way to call native (c, c++, etc) functions from within Java. A class can define a "native" method that, when invoked, actually calls some function on the native side. In this post, I am going to walk through a simple example using Java 1.4.2 and the MINGW C++ compiler in windows.
The Java Side: HelloWorldJNI.java
public class HelloWorldJNI {
// Load the native methods from a shared library
static { System.loadLibrary("hello"); }
public HelloWorldJNI() { }
public native void helloWorldNative();
public void helloWorldJava() {
System.out.println("Hello World (from java side)");
}
public static void main(String [] args) {
HelloWorldJNI helloWorld = new HelloWorldJNI();
helloWorld.helloWorldJava();
helloWorld.helloWorldNative();
}
}
The C++ Side: HelloWorldJNI.cpp
#include <jni.h>
#include <iostream>
#include "HelloWorldJNI.h"
using namespace std;
JNIEXPORT
void JNICALL Java_HelloWorldJNI_helloWorldNative(JNIEnv *env, jobject thisObject) {
cout << "Hello World (from native side)" << endl;
}
Compiling and Linking
In windows using java and mingw:
javac -cp . HelloWorldJNI.java
javah HelloWorldJNI
c++ -g -O2 -c -I%JAVA_HOME%/include -I%JAVA_HOME%/include/win32 HelloWorldJNI.cpp
dllwrap --driver-name=c++ --add-stdcall-alias -o hello.dll -s HelloWorldJNI.o
Download Example
Project files may be downloaded from the following location: JNI_Example.zip