我的NDK学习开发笔记(一)

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;
}
ReleaseStringUTFChars与delete 功能相同,使用后效果一样,应该可以随意使用。
//log使用时需要添加ldLibs "log"//实现__android_log_print
位置如下:
ndk {
moduleName"xccJnis"
ldLibs"log"//实现__android_log_print
abiFilters'armeabi','x86','armeabi-v7a','arm64-v8a','x86_64'
//输出指定三种abi体系结构下的so库。
}

添加其他C++标准库支持

#include <string>//提示找不到string时,需要添加C++其他标准库
添加以下两行即可
stl ="stlport_shared"//添加其他C++标准库支持
cFlags("-std=c++11")
完整配置如下

ndk {
moduleName"xccJnis"
ldLibs"log"//实现__android_log_print
stl ="stlport_shared"//添加其他C++标准库支持
cFlags("-std=c++11")
abiFilters'armeabi','x86','armeabi-v7a','arm64-v8a','x86_64'
//输出指定三种abi体系结构下的so库。
}
如果是eclipse,需要将Application.mk放在jni目录下(内容如下)
APP_STL := stlport_static

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;
}
}

注:int*ints = new int[16];更改成int*ints = new int[160*1024*1024];。然后多次调用测试发现new 比 malloc 更加稳定,malloc会出现申请失败,可能是之前释放失败等多种原因导致,但是new都是可以成功申请到内存。SO,不建议使用malloc。
注:将delete注释掉,然后多次调用导致程序闪退。说明new在申请内存时,申请不到内存会崩溃。而malloc申请不到内存是不会崩溃。SO,new出来的对象一定得记得delete。

学习时编写的完整代码,下载地址:
码云:http://git.oschina.net/rookieci/NDKStudy
github:https://github.com/cookieci/NDKStudy













































發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章