Clicky

ChrisEllsworth.com

The online home of Christopher Chess Ellsworth
Welcome to ChrisEllsworth.com Sign in | Join | Help
in Search

Chris's Development Blog

Tutorials and thoughts on software development.

Java Native Interface Example

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

 

Published Tuesday, February 08, 2005 8:56 PM by Christopher Chess Ellsworth
Filed under: , ,

Attachment(s): http://www.cs.appstate.edu/~cce/downloads/JNI_Example.zip

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit

Locations of Visitors

Locations of visitors to this page
©2007 Christopher Chess Ellsworth