本文为 Core Java Volume II Advanced Features 11th.Edition笔记,介绍如何使用JNI接口,主要用于java调用本地接口(C,CPP)
目录
Why native code might be the right choice
Calling a C Function from a Java Program
1. Declare a native method in a Java class
2. Run javah to get a header file with a C declaration for the method
3. Implement the native method in C
4. your Java program to load the library
Numeric Parameters and Return Values
Why native code might be the right choice
- Your application requires access to system features or devices that are not accessible through the Java platform.
- You have substantial amounts of tested and debugged code in another language, and you know how to port it to all desired target platforms.
- You have found, through benchmarking, that the Java code is much slower than the equivalent code in another language.
Calling a C Function from a Java Program
1. Declare a native method in a Java class
2. Run javah to get a header file with a C declaration for the method
javac -h . HelloNative.java
The macros JNIEXPORT and JNICALL are defined in the header file jni.h. They denote compiler-dependent specifiers for exported functions that come from a dynamically loaded library.
3. Implement the native method in C
Linux: gcc -fPIC -I jdk/include -I jdk/include/linux -shared -o libHelloNative.so HelloNative.c
Windows: cl -I jdk\include -I jdk\include\win32 -LD HelloNative.c -FeHelloNative.dll
4. your Java program to load the library
To ensure that the JVM will load the library before the first use of the class, use a static initialization block.
5. Place the code in a shared library and run it
Numeric Parameters and Return Values
String Parameters
GetStringUTFChars returns a pointer to the “modified UTF-8” encoding of a string. The pointer is valid until ReleaseStringUTFChars is called. The 3rd parameter is filled with JNI_TRUE if the array is a copy. If you aren’t interested in that information, just pass a NULL pointer.
NewStringUTF returns a new Java string object from a zero byte-terminated “modified UTF-8” byte sequence
ReleaseStringUTFChars informs the virtual machine that the native code no longer needs access to the Java string through chars (a pointer returned by GetStringChars).
Accessing Fields
Encoding Signatures
To describe an array type, use a [. E.g., A float[][] is mangled into [[F, method receiving two integers and returning an integer is encoded as (II)I
Calling Java Methods
Accessing Array Elements
Using the Invocation API
The invocation API enables you to embed the Java virtual machine into a C or C++ program.
gcc -I jdk/include -I jdk/include/linux -o InvocationTest \ -L jdk/jre/lib/i386/client -ljvm InvocationTest.c