Notes About JNI

Note #0:

How to create JNI:

public class AJNIClass {

static {

private native static void aMethod (int aParam, String aParamToo, byte[] yetAnotherParam);


Note #1:

There are two ways of loading native library:
  1. Using "System.load". This is like loading a file. 
  2. Using "System.loadLibrary". This is like asking JVM loader to search in system path the right library.
    Example: System.loadLibrary("SMJava"); will try to load in *nix or SMJava.dll in Windoze.
Note #2:

How to create JNI Code:

# javac
# javah AJNIClass

It will generate a header. Implement it and compile the arbitary library. Voila! Your program will start to run (of course with bug included).

Note #3:

A pointer in C/C++ is an integer long in the Java. So, you can save pointers in Java. Java will prevent its Garbage Collector from erasing the memory where the data inhabitate. So, be sure to free the memory after using it.

Note #4:

People always use static branch of  a class to load a native. This isn't a bad idea since the library is loaded once when the class is loaded. But, to give you a fairness and control, you could load the native library in any static method. The main method may applicable, this is necessary in times where you want to walk with many platform supported and you may choose which library should be loaded. Oh, with the Singleton around, maybe it can be suitable for non static object. But, I've never tried it before.

Note #5:

There is a God, pray when you see a segmentation fault. :P


Popular Posts