通过javah命令得到.h文件:
#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文件:
#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配置中添加下面一行代码:
ldLibs "log"
注:通过JNI GetStringChars函数和GetStringUTFChars函数获得的C字符串在原生代码中使用完后需要正确释放,否则将会引起内存泄露,其中释放函数为ReleaseStringChars和ReleaseStringUTFChars