Ubuntu 使用Jni開發(fā)實(shí)例詳解
1. 編寫Java文件,在其中聲明native方法, 并通過(guò)static 語(yǔ)句塊加載動(dòng)態(tài)鏈接庫(kù),示例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.調(diào)用javac命令生成Prompt.class文件;
javac Prompt.java
3.調(diào)用javah命令生成Prompt.h頭文件供C程序引用:
javah -jni Prompt
自動(dòng)生成的頭文件如下:
/* 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文件實(shí)現(xiàn)具體功能:
#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ì)本站的支持!
相關(guān)文章
IDEA 中創(chuàng)建Spring Data Jpa 項(xiàng)目的示例代碼
這篇文章主要介紹了IDEA 中創(chuàng)建Spring Data Jpa 項(xiàng)目的示例代碼,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04SpringBoot整合Swagger接口文檔工具的流程步驟
我們?cè)陂_發(fā)接口的時(shí)候,會(huì)將接口文檔給前端的開發(fā)者進(jìn)行對(duì)接,我們可以通過(guò)Postman或者Yapi等接口管理工具進(jìn)行編寫管理,實(shí)際開發(fā)中,接口的管理確實(shí)也應(yīng)該通過(guò)專業(yè)的工具管理,本文,我們就來(lái)談?wù)勗趺丛赟pringBoot整合Swagger接口文檔工具2023-08-08設(shè)計(jì)模式之原型模式_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了設(shè)計(jì)模式之原型模式,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08Mybatis?一級(jí)緩存和二級(jí)緩存原理區(qū)別
這篇文章主要介紹了Mybatis?一級(jí)緩存和二級(jí)緩存原理區(qū)別?,文章通過(guò)圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09