JNI Android - 将 char* 转换为字节数组并将其返回给 java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17124712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:03:59  来源:igfitidea点击:

JNI Android - Converting char* to byte array and return it to java

javaandroidcandroid-ndk

提问by Vektor88

I initially used a function to return a char* to java as UTF-8 string, but since I kept getting errors, I wrote the following function to return a char*as a Java byte[], so that I could try to convert the array into a String in java side:

我最初使用一个函数将 char* 作为 UTF-8 字符串返回给 java,但由于我不断收到错误,我编写了以下函数以将 achar*作为 Java返回byte[],以便我可以尝试将数组转换为 String java端:

jbyteArray Java_com_vektor_amapper_util_InputDeviceManager_getDevNameBytes(JNIEnv* env, jobject thiz, jint index) {
    if(pDevs[index].device_name == NULL) return NULL;
    int n=0;
    while(pDevs[index].device_name){
        n++;
    } if (n==0) return NULL;
    jbyteArray arr = (*env)->NewByteArray(env, n);
    (*env)->SetByteArrayRegion(env,arr,0,n, (jbyte*)pDevs[index].device_name);
    return arr;
}

But when I call it my application crashes. Am I missing something?

但是当我调用它时,我的应用程序崩溃了。我错过了什么吗?

Update:The condition was missing a ++ and this caused an infinite loop. But now with the following code:

更新:条件缺少 ++,这导致了无限循环。但是现在使用以下代码:

jbyteArray Java_com_vektor_amapper_util_InputDeviceManager_getDevNameBytes(JNIEnv* env, jobject thiz, jint index) {
    int n=0;
    if(pDevs[index].device_name == NULL) return NULL;
    while(pDevs[index].device_name++){
        n++;
    } if(n==0) return NULL;
        jbyteArray arr = (*env)->NewByteArray(env, n);
        (*env)->SetByteArrayRegion(env,arr,0,n, (jbyte*)pDevs[index].device_name);
        return arr;
}

I get this weird JNI warning:

我收到这个奇怪的 JNI 警告:

06-15 22:40:02.303: W/dalvikvm(7616): JNI WARNING: negative jsize (NewByteArray)

06-15 22:40:02.303:W/dalvikvm(7616):JNI 警告:负 jsize (NewByteArray)

How can it be since I am only increasing the value of n?

怎么会因为我只是增加了 的价值n

Update 2:the following code works:

更新 2:以下代码有效:

jbyteArray Java_com_vektor_amapper_util_InputDeviceManager_getDevNameBytes(
        JNIEnv* env, jobject thiz, jint index) {

    if(pDevs[index].device_name == NULL) return NULL;
    int n=0;
    char* p = pDevs[index].device_name;
    while(*p++){
        n++;
    } if(n<=0) return NULL;
    jbyteArray arr = (*env)->NewByteArray(env, n);
    (*env)->SetByteArrayRegion(env,arr,0,n, (jbyte*)pDevs[index].device_name);

    return arr;
}

采纳答案by xqterry

Shouldn't be this ?

不应该是这个吗?

char* p = pDevs[index].device_name;
while( *p++) {
...
}