1. 首先建立要使用JNI的 JavaCallC.java 檔 以及 要被JNI呼叫的 JavaCallC.c 檔
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <jni.h> | |
#include "JavaCallC.h" | |
#include <stdio.h> | |
JNIEXPORT void JNICALL | |
Java_JavaCallC_csayhello(JNIEnv *env, jobject obj) | |
{ | |
printf("Hello world from C Language JavaCallC.c csayhello!\n"); | |
return; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.*; | |
public class JavaCallC { | |
public JavaCallC (){ | |
System.loadLibrary("JavaCallC"); | |
} | |
public native void csayhello(); | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
new JavaCallC().csayhello(); | |
} | |
} |
javac JavaCallC.java
javah -jni JavaCallC
3. 產生 libJavaCallC.so
gcc -shared -I /opt/java/jdk1.7.0_21/include/ -I /opt/java/jdk1.7.0_21/include/linux/ JavaCallC.c -o libJavaCallC.so
4. 執行
java -Djava.library.path=. JavaCallC
5.結果輸出
Hello world from C Language JavaCallC.c csayhello!
參考資料