“Android Studio”下“JNI”開發(linux.ubuntu)過程
JNI常用函數大全
傳遞String字符串
#MainActivity.java:
JNI jni = new jni();//實例化JNI對象
jni.helloFromC("world!");//調用本地方法
#JNI.java:
public class JNI{
static{
System.loadLibrary("hello-jni");//加載libhello-jni.so庫
}
public static native String helloFromC(String key);//聲明本地方法
}
#hello-jni.h:
#include <jni.h>
#ifndef _Included_com_example_wlf_callashleyt_JNI
#defin _Included_com_example_wlf_callashleyt_JNI
#ifdef __cplusplus
extern "C"{
#endif
JNIEXPORT jstring JNICALL Java_com_example_wlf_callashleyt_JNI_helloFromC
(JNIEnv, jclass,jsting);
#ifdef __cpusplus
}
#endif
#endif
#hello-jni.c:
#include <jni.h>
jstring charToJstring(JNIEnv*,const char*);//byte[]數組轉jstring
JNIEXPORT jstring JNICALL Java_com_example_wlf_callashleyt_JNI_helloFromC
(JNIEnv *env, jclass obj,jsting key){
/*
先將key類型由jstring轉爲char*
/*
const char *str = (*env)->GetStringUTFChars(env,key,0);
if(str == NULL)
return NULL;
char buf[50] = "Hello:";
strcat(buf,str);//字符串拼接
(*env)->ReleaseStringUTFChars(env,key,str);
return charToJstring(env,buf);//字符串處理後再轉回jstring,以傳遞迴java
//見[getMethodID函數解釋及方法簽名]
}
jstring charToJstring(JNIEnv* env,const char* str){
jclass clstring = (*env)->FindClass("java/lang/String");
//獲取對象
jmethodID mid = (*env)->GetMethodID(env,clstring,"<init>","([BLjava/lang/String;)V");//獲取String(byte[],String)的構造器,用於將本地byte[]數組轉換爲一個新String
jbyteArray bytes = (*env)->NewByteArray(env,strlen(str));//建立jbyte數組
(*env)->SetByteArrayRegion(bytes, 0, strlen(str), (jbyte*) str);//將char* 轉換爲byte數組
jstring encoding = (env)->NewStringUTF("utf-8");// 設置String, 保存語言類型,用於byte數組轉換至String時的參數
return (jstring) (env)->NewObject(strClass, ctorID, bytes, encoding);//將byte數組轉換爲java String,並輸出
}