JNI 讓 Java 能呼叫 C 或 C++ 寫成的原生程式。以下以一個「讀取使用者輸入」的小例子,走過在 Ubuntu 上從 Java 宣告、產生標頭檔、撰寫 C 實作到編譯成動態庫並執行的每一步。
用 native 修飾方法,並在 static 區塊中載入動態連結庫。以 Prompt.java 為例:
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");
}
}
javac Prompt.java
javah -jni Prompt
自動產生的 Prompt.h 內容如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Prompt */
#ifndef _Included_Prompt
#define _Included_Prompt
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Prompt
* Method: getLine
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_Prompt_getLine
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
#include <jni.h>
#include <stdio.h>
#include "Prompt.h"
JNIEXPORT void 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);
}
編譯時必須把 JDK 的 include 目錄加進搜尋路徑,-shared -fpic 則是產生位置無關的共享物件:
gcc -shared -fpic \ -I/usr/lib/jvm/java-6-sun-1.6.0.26/include \ -I/usr/lib/jvm/java-6-sun-1.6.0.26/include/linux \ Prompt.c -o libPrompt.so
實際操作時,請把路徑換成你機器上 JDK 的安裝位置。
java Prompt
動態庫的名稱要與 System.loadLibrary() 的參數一致,且檔案必須放在 java.library.path 會搜尋到的目錄,否則會丟出 UnsatisfiedLinkError。還要注意 JNI 的字串編碼轉換:用 GetStringUTFChars 借到的記憶體一定要用 ReleaseStringUTFChars 歸還,回傳值則要透過 NewStringUTF 建立新的 Java 字串物件。