C++ std::string to jstring with a fixed length

前端 未结 1 850
没有蜡笔的小新
没有蜡笔的小新 2021-02-19 21:13

I\'m trying to turn a C++ std::string into a jstring and return it. This would be easy enough with

JNIEnv*->NewStringUTF(stdString.c_str())

1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-19 21:41

    I made my own workaround solution taking RedAlert's advice.

    Java now expects a byte[] from the native call:

    private native byte[] toString(long thiz);
    

    The toString method now calls this method inside it on a std::string:

    jbyteArray StringToJByteArray(JNIEnv * env, const std::string &nativeString) {
        jbyteArray arr = env->NewByteArray(nativeString.length());
        env->SetByteArrayRegion(arr,0,nativeString.length(),(jbyte*)nativeString.c_str());
        return arr;
    }
    

    And the java level receives the data like this:

    byte[] byteArray = toString(mNativeInstance);
    String nativeString = "";
    try {
        nativeString = new String(byteArray, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "Couldn't convert the jbyteArray to UTF-8");
        e.printStackTrace();
    }
    

    0 讨论(0)
提交回复
热议问题