Jni:jbyteArray->char* 及char*->jbyteArray

//调用Android原生log打印功能
#include 
#define LOG_TAG    "jni>>"
#define LOGE(format, ...)  __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, format, ##__VA_ARGS__)
//传入byte[]输出byte[]
extern "C"
JNIEXPORT jbyteArray JNICALL
Java_com_mysterycode_myjni_MainActivity_convertByte(JNIEnv *env, jobject thiz, jbyteArray source) {
//------jbyteArray -> char*------
    jbyte *jb = env->GetByteArrayElements(source, JNI_FALSE);
    int chars_len = env->GetArrayLength(source);
    char *chars = new char[chars_len + 1];
    memset(chars, 0, chars_len + 1);
    memcpy(chars, jb, chars_len + 1);
    //末尾补0以终止
    chars[chars_len] = 0;
    env->ReleaseByteArrayElements(source, jb, 0);
    LOGE("cb>>%c", chars[0] + 80);//%c为站位符,%c->char*,%s->char*
    for(int i=0;i jbyteArray------
    jbyteArray ja=env->NewByteArray(chars_len);
    jbyte *b=env->GetByteArrayElements(ja,JNI_FALSE);//获取byte[]地址
    memcpy(b,chars, chars_len);//复制实际内容
    env->SetByteArrayRegion(ja,0,chars_len,b);//**从C向Java提交操作(关键)**
    env->ReleaseByteArrayElements(ja, b, 0);//释放指针,避免内存泄漏

    return ja;
}

 

你可能感兴趣的:(Jni,Android)