Java Native Methods Interface


Another feature of Java is that C and C++ functions can be used by using java native interface.

In this project, a C version of the arithmetic functions are implemented and are used both in client and server side.
I will briefly explain how native functions are implemented in this project.

  • 1. First a Java object that have native functions calls is created This would be: native/Arithmetic.java Basically, if we look at this code:
            static {
                    System.loadLibrary("Arithmetic");
            }
            // calls for native C functions
            public native int Add(int a, int b);
    	.......
    
    A Java method loadLibrary() is used to load the library Arithmetic which is going to be implemented. This library must have the functions which are defined as public native
  • Then, it is compiled by using
    	% javac Arithmetic.java
    
  • After that, we need to create the header files for the C program. This is done by using:
    	% javah -jni Aritmetic
    
    This header holds the function declarations: native/Arithmetic.h (In order to access this file the system must be built!:)
  • Then, we created the C file:native/Arithmetic.c. You should include Arithmetic.h file and jni.h which is located in the Java include directory. When using function calls, you should be careful about Java's naming conventions.
  • Then we compiled the C code to create a .so, shared object file.(If you are in a Windows system, you should create a DLL). The shared object is created like this:
         % cc -G Arithmetic.c -I/afs/bp.ncsu.edu/contrib/jdk117/java/include \
           -I/afs/bp.ncsu.edu/contrib/jdk117/java/include/solaris -o libArithmetic.so
    
    The pathnames are specific to the environment that we used. If you use a different environment, change pathnames accordingly.
  • Now you can use Arithmetic.class and libArithmetic.so files to call native functions!

    For more information about JNI, these links can be checked out: