Ubuntu 應用Jni開辟實例詳解。本站提示廣大學習愛好者:(Ubuntu 應用Jni開辟實例詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是Ubuntu 應用Jni開辟實例詳解正文
1. 編寫Java文件,在個中聲明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");
}
}
2.挪用javac敕令生成Prompt.class文件;
javac Prompt.java
3.挪用javah敕令生成Prompt.h頭文件供C法式援用:
javah -jni Prompt
主動生成的頭文件以下:
/* 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.編寫Prompt.c文件完成詳細功效:
#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. 編譯靜態庫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. 運轉。
java Prompt
感激浏覽,願望能贊助到年夜家,感謝年夜家對本站的支撐!