經過javah命令獲得.h文件:java
#include <jni.h> /* Header for class com_learn_ndk_StringProcess */ #ifndef _Included_com_learn_ndk_StringProcess #define _Included_com_learn_ndk_StringProcess #ifdef __cplusplus extern "C" { #endif /* * Class: com_learn_ndk_StringProcess * Method: passStringReturnString * Signature: (Ljava/lang/String;)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_com_learn_ndk_StringProcess_passStringReturnString (JNIEnv *, jclass, jstring); #ifdef __cplusplus } #endif #endif
而後建立一個.c文件:android
#include <jni.h> #include <android/log.h> #include <string.h> #include "StringProcess.h" #define LOG_TAG "StringProcess" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) JNIEXPORT jstring JNICALL Java_com_learn_ndk_StringProcess_passStringReturnString (JNIEnv *env, jclass obj, jstring jstr) { jboolean *isCopy; jbyte *pchar; pchar = (*env)->GetStringUTFChars(env, jstr, isCopy); if (pchar == NULL) { LOGI("Can not convert jstring to utf-8 string"); } jsize length = (*env)->GetStringLength(env, jstr); LOGI("UTF-8 string length (number of bytes): %d == %d", length, strlen(pchar)); (*env)->ReleaseStringUTFChars(env, jstr, pchar); char nativeStr[100] = {0}; (*env)->GetStringUTFRegion(env, jstr, 0, length, nativeStr); LOGI("jstring converted to UYT-8 string and copied to native buffer: %s", nativeStr); const char *newStr = "hello 安卓"; jstring ret = (*env)->NewStringUTF(env, newStr); jsize newStrLen = (*env)->GetStringUTFLength(env, ret); LOGI("UTF-8 string with Chinese characters: %s, string length (number of bytes) %d=%d", newStr, newStrLen, strlen(newStr)); return ret; }
其中#include<android/log.h>引用了log,須要在app文件下的build.grandle文件的ndk配置中添加下面一行代碼:app
ldLibs "log"
注:經過JNI GetStringChars函數和GetStringUTFChars函數得到的C字符串在原生代碼中使用完後須要正確釋放,不然將會引發內存泄露,其中釋放函數爲ReleaseStringChars和ReleaseStringUTFChars函數