How do I convert jstring to wchar_t *

前端 未结 10 841
闹比i
闹比i 2020-12-01 14:48

Let\'s say that on the C++ side my function takes a variable of type jstring named myString. I can convert it to an ANSI string as follows:

相关标签:
10条回答
  • 2020-12-01 15:33

    I know this was asked a year ago, but I don't like the other answers so I'm going to answer anyway. Here's how we do it in our source:

    wchar_t * JavaToWSZ(JNIEnv* env, jstring string)
    {
        if (string == NULL)
            return NULL;
        int len = env->GetStringLength(string);
        const jchar* raw = env->GetStringChars(string, NULL);
        if (raw == NULL)
            return NULL;
    
        wchar_t* wsz = new wchar_t[len+1];
        memcpy(wsz, raw, len*2);
        wsz[len] = 0;
    
        env->ReleaseStringChars(string, raw);
    
        return wsz;
    }
    

    EDIT: This solution works well on platforms where wchar_t is 2 bytes, some platforms have a 4 byte wchar_t in which case this solution will not work.

    0 讨论(0)
  • 2020-12-01 15:36

    If we are not interested in cross platform-ability, in windows you can use the MultiByteToWideChar function, or the helpful macros A2W (ref. example).

    0 讨论(0)
  • 2020-12-01 15:38

    JNI has a GetStringChars() function as well. The return type is const jchar*, jchar is 16-bit on win32 so in a way that would be compatible with wchar_t. Not sure if it's real UTF-16 or something else...

    0 讨论(0)
  • 2020-12-01 15:39

    Just use env->GetStringChars(myString, 0); Java pass Unicode by it's nature

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