The JNI is designed to handle situations where you need to combine Java applications with native code. As a two-way interface, the JNI can support two types of native code: native libraries and native applications.
JNI就是让Java代码与native代码(比如C和C++)交互的一种机制。
《The JNI Programmer's Guide and Specification》
--http://java.sun.com/docs/books/jni/html/intro.html#994
首先编辑一个Java文件Prompt.java
public class Prompt { private native String getLine(String prompt); public static void main(String[] args) { Prompt p = new Prompt(); String input = p.getLine("Type a line: "); System.out.println("User typed: " + input); } static { System.loadLibrary("Prompt"); }}
其中native用来声明一个方法,而方法的实现则交给C代码。static代码块用来加载接下来即将生成的libPrompt.so
然后编译刚才的Prompt.java,并通过javah生成一个C语言的头文件
javac Prompt.javajavah -jni Prompt
这样就生成了一个Prompt.h文件,接下来编辑Prompt.c
#include <stdio.h>#include <jni.h>#include "Prompt.h"JNIEXPORT jstring JNICALL Java_Prompt_getLine(JNIEnv *env, jobject obj, jstring prompt) { char buf[128]; const jbyte *str; str = (*env)->GetStringUTFChars(env, prompt, NULL); if (str == NULL) { return NULL; } printf("%s", str); (*env)->ReleaseStringUTFChars(env, prompt, str); scanf("%s", buf); return (*env)->NewStringUTF(env, buf);}
编译Prompt.c来生成libPromt.so,虽然有些warning,不过还是能编译通过的
gcc -shared -fPIC -I /opt/java/include/ -I /opt/java/include/linux/ Prompt.c -o libPrompt.so
于是,可以运行了
java -Djava.library.path=. Prompt