Using javah to create JNI interfaces

There are times that you will need to interface with the underlying operating system APIs or you have a dynamic link libraries that needs to be called from Java. It can be done using JNI using the javah tool.

First, you will need to create a java class that expose interfaces that you will implement in C.
////////////////////////////////// MyJavaInterfaces.java ////////////////////////////////////
public class MyJavaInterfaces{

    public MyJavaInterfaces(){
    }

    public native int MyFunction();

    static{
        System.loadLibrary("MyNativeInterfaces");
    }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////

The declaration, public native int MyFunction(); is the native function that needs to be
implemented in C. The call, System.loadLibrary("MyNativeInterfaces"); is the library
that you will create and in it is your native function implementation. So, after creating your
java class above compile it using javac tool and a MyJavaInterfaces.class is created. Using the
javah tool in the commandline like, javah -jni "MyJavaInterfaces" will create a C header
file with declaration of your native function. Open it and explore the file.

At this time you will need to create the library MyNativeInterfaces implementing the MyFunction.

////////////////////////////////////// MyNativeInterfaces.cpp////////////////////////////////////////
#include

#include "MyJavaIntefaces.h"

JNIEXPORT jint JNICALL Java_MyJavaInterfaces_MyFunction
(JNIEnv* jnienv, jobject service)
{

        jint status=0;
        return status;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

The example above function will just return 0 back to java call. Of course you will need
to create the library with this code. Refer to your compiler manual on how to create the library
in your chosen platform.

Comments

Popular posts from this blog

Creating tray application and popup context menu in Windows

How to statically link applications to wxWidgets via Visual Studio 2008 and in Linux

How to put an image to wxPanel using wxWidgets