1. 編寫(xiě)Java文件,在其中聲明native方法, 并通過(guò)static 語(yǔ)句塊加載動(dòng)態(tài)鏈接庫(kù),示例Prompt.java代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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" ); } } |
2.調(diào)用javac命令生成Prompt.class文件;
javac Prompt.java
3.調(diào)用javah命令生成Prompt.h頭文件供C程序引用:
javah -jni Prompt
自動(dòng)生成的頭文件如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
/* 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 |
4.編寫(xiě)Prompt.c文件實(shí)現(xiàn)具體功能:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#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); } |
5. 編譯動(dòng)態(tài)庫(kù)libPrompt.so;
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
6. 運(yùn)行。
java Prompt
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!