NDK使用Log,jstring到char*
#include "com_xcc_ndkstudy_GetString.h"
#include <string.h>
#include <android/log.h>
#define LOG_TAG "--xcc-native-dev--"
//定義log使用
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
jstring Java_com_xcc_ndkstudy_GetString_stringToJni(JNIEnv *jniEnv, jobject jobj) {
LOGI("test");
jstring jStr = jniEnv->NewStringUTF("磁磁帥");
jboolean isCopy;
//將jstring轉到char*
const char *str = jniEnv->GetStringUTFChars(jStr, &isCopy);
if (0 != str) {
LOGI("test%s", str);
}
//回收str
jniEnv->ReleaseStringUTFChars(jStr, str);
//delete str;
LOGI("test%s", str);
str = 0;
return jStr;
}
添加其他C++標準庫支持
C/C++申請內存
#include "com_xcc_app2_XccLibs.h"
#include <string.h>
#include <android/log.h>
#include <stdlib.h>
#define LOG_TAG "--xcc-native-dev--"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
void Java_com_xcc_app2_XccLibs_cRun(JNIEnv * env, jobject jObj){
LOGI("--磁磁帥-->");
int *intArrays = (int *) malloc(sizeof(int) * 16);
if(NULL==intArrays){
LOGI("--申請內存失敗-->");
}else{
LOGI("--申請內存成功-->");
*intArrays = 4;
intArrays++;
*intArrays = 2;
LOGI("--打印值-->%d", *intArrays);
intArrays--;
LOGI("--打印值-->%d", *intArrays);
LOGI("--15打印值-->%d", intArrays[15]);
LOGI("--改變申請到的內存大小-->");
intArrays = (int *) realloc(intArrays, sizeof(int) * 32);
free(intArrays);//釋放內存
intArrays = NULL;
}
//C++ 申請內存
int *ints = new int[16];
if(NULL==ints){
LOGI("--C++申請內存失敗-->");
}else{
LOGI("--C++申請內存成功-->");
ints++;
*ints=10;
LOGI("--打印值-->%d", *ints);
ints--;
/**
* 注:ints[1]相當於 ints+=1; *ints; ints-=1;
*/
LOGI("--打印值-->%d", ints[1]);
delete ints;
}
}
碼雲:http://git.oschina.net/rookieci/NDKStudy
github:https://github.com/cookieci/NDKStudy