JNI
example #
1. 写一段包含C方法实现的java代码 #
The static initializer invokes System.loadLibrary() to load the native library “hello” (which contains a native method called sayHello()) during the class loading. It will be mapped to “hello.dll” in Windows; or “libhello.so” in Unixes/Mac OS X. This library shall be included in Java’s library path (kept in Java system variable java.library.path). You could include the library into Java’s library path via VM argument -Djava.library.path=/path/to/lib. The program will throw a UnsatisfiedLinkError if the library cannot be found in runtime.
2. 编译HelloJNI.java 并且生成C/C++头文件 HelloJNI.h #
Starting from JDK 8, you should use “javac -h” to compile the Java program AND generate C/C++ header file called HelloJNI.h as follows:javac -h . HelloJNI.java
The “-h dir” option generates C/C++ header and places it in the directory specified (in the above example, ‘.’ for the current directory).Before JDK 8, you need to compile the Java program using javac and generate C/C++ header using a dedicated javah utility, as follows. The javah utility is no longer available in JDK 10.javac HelloJNI.java
javah HelloJNI
3. 实现C语言代码 #
4. 编译HelloJNI.c #
- Set environment variable JAVA_HOME to point to the JDK installed directory (which shall contains the include subdirectory to be used in the next step):
- Compile the C program HelloJNI.c into dynamic share module libhello.dylib using gcc, which is included in all Unixes/Mac OS:
- Run the Java Program:
- Set environment variable JAVA_HOME to point to the JDK installed directory (which shall contains the include subdirectory to be used in the next step):
- Compile the C program HelloJNI.c into share module libhello.so using gcc, which is included in all Unixes:
- Run the Java Program: