search

Home  >  Q&A  >  body text

android - JNI c语言里的char数组怎么转成java的char数组?

java的实体里定义的char[] name JNI定义结构体属性char[] name将结构体属性值(中文)传给java是乱码,怎么解决?不要让我改变属性类型!

黄舟黄舟2835 days ago818

reply all(3)I'll reply

  • PHPz

    PHPz2017-04-17 17:53:41

    Please refer to this article

    You must first figure out what the codes are on both sides.

    reply
    0
  • 迷茫

    迷茫2017-04-17 17:53:41

    The char[] string in C is UTF-8 encoded by default. You can use the NewStringUTF() function of JNIEnv to convert the char[] string in C to a Java string. The signature of this function is:

    jstring NewStringUTF(const char* bytes)

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 17:53:41

    Look at the simplest example:

    JNIEXPORT jstring JNICALL Java_com_example_gnaix_ndk_NativeMethod_getString
            (JNIEnv *env, jclass object, jstring str){
    
        //1. 将unicode编码的java字符串转换成C风格字符串
        const char *buf_name = env->GetStringUTFChars(str, 0);
        if(buf_name == NULL){
            return NULL;
        }
        int len = strlen(buf_name);
        char n_name[len];
        strcpy(n_name, buf_name);
    
        //2. 释放内存
        env->ReleaseStringUTFChars(str, buf_name);
    
        //3. 处理 n_name="ro.serialno"
        char buf[1024];
        __system_property_get(n_name, buf);
        LOGD("serialno : %s", buf);
    
        //4. 去掉尾部"rrreee"
        int len_buf = strlen(buf);
        string result(buf, len_buf);
    
        return env->NewStringUTF(result.c_str());
    }

    reply
    0
  • Cancelreply