jstring return in JNI program

前端 未结 2 882
北海茫月
北海茫月 2021-01-01 10:48

This is JNI code.

Java code:

public class Sample1 {
 
    public native String stringMethod(String te         


        
相关标签:
2条回答
  • 2021-01-01 11:40

    this should be the way to do it....

    JNIEXPORT jstring JNICALL Java_Sample1_stringMethod
        (JNIEnv *env, jobject obj, jstring string) 
    {    
        const char *name = (*env)->GetStringUTFChars(env,string, NULL);
        char msg[60] = "Hello ";
        jstring result;
        
        strcat(msg, name);  
        (*env)->ReleaseStringUTFChars(env,string, name);   
        puts(msg);            
        result = (*env)->NewStringUTF(env,msg); 
        return result;        
    }
    
    0 讨论(0)
  • 2021-01-01 11:44

    There are several ways but the best I got by converting const char * to c++ string and then to jbyteArray, and its easy to conversion of byteArray to UTF-8 on java side.

    C++ side:

    const char* string = propertyValue;
    std::string str = string;
    
    jbyteArray array = env->NewByteArray(str.length());
    env->SetByteArrayRegion(array,0,str.length(),(jbyte*)str.c_str());
    
    
    return array;
    

    Java/kotlin side:

    String((array), Charset.defaultCharset()))
    
    0 讨论(0)
提交回复
热议问题