Ben Chuanlong Du's Blog

It is never too late to learn.

Java Native Access

Java Native Interface

  1. You can call native code (typically C, C++ or Fortran) in Java using the Java Native Interface (JNI). For the code implemented in native code, you must use keyword "native" to tell the compiler that it is implemented outside Java. Also, you should surround the Java code which load the compile native code in static{} (i.e. static initialized). This will get executed when Java load the class. For more information, please refer to Calling C library Routines from Java

  2. javacpp seems to be another good option.

Java Native Access

  1. Java Native Access is a more convenient way to call native code than the Java Native Interface. It is based on Java Native Interface

An example of calling a system DLL/SO/dynamic load.

In [ ]:
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;

public class TestSystemDLL {
	public interface CLibrary extends Library {
        CLibrary INSTANCE = (CLibrary)
            Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"),
                               CLibrary.class);
   
        void printf(String format, Object... args);
    }
 
    public static void main(String[] args) {
        CLibrary.INSTANCE.printf("Hello, World\n");
        for (int i=0;i < args.length;i++) {
            CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
        }
    }
}

An example of calling a user SO.

In [ ]:
import com.sun.jna.Library;
import com.sun.jna.Native;

public class TestUserDLL {
	public interface MyDLL extends Library {
		
		MyDLL INSTANCE = (MyDLL) Native.loadLibrary("/home/dclong/test/sum.so",
				MyDLL.class);

		public double sum(double x, double y);

	}

	public static void main(String[] args) {
		System.out.println(MyDLL.INSTANCE.sum(1,2));
	}
}
In [ ]:

Comments