tags:

views:

2219

answers:

6

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:

const char* ansiString = env->GetStringUTFChars(myString, 0);

is there a way of getting

const wchar_t* unicodeString = ...

+1  A: 

A portable and robust solution is to use iconv, with the understanding that you have to know what encoding your system wchar_t uses (UTF-16 on Windows, UTF-32 on many Unix systems, for example).

If you want to minimise your dependency on third-party code, you can also hand-roll your own UTF-8 converter. This is easy if converting to UTF-32, somewhat harder with UTF-16 because you have to handle surrogate pairs too. :-P Also, you must be careful to reject non-shortest forms, or it can open up security bugs in some cases.

Chris Jester-Young
A: 

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

1800 INFORMATION
+1  A: 

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...

Adam Mitz
Do you happen to know if jchar's byte ordering is compatible with the Win32 wchar_t one? It should be, but probably good to be sure. :-)
Chris Jester-Young
jchar is typedef'ed to unsigned short. I haven't tried it myself but my guess would be "yes".
Adam Mitz
A: 

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

A: 

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;
}
Benj
A: 

And who frees wsz? I would recommend STL!

std::wstring JavaToWSZ(JNIEnv* env, jstring string)
{
    std::wstring value;
    if (string == NULL) {
        return value; // empty string
    }
    const jchar* raw = env->GetStringChars(string, NULL);
    if (raw != NULL) {
        jsize len = env->GetStringLength(string);
        value.assign(raw, len);
        env->ReleaseStringChars(string, raw);
    }
    return value;
}
Andreas Rieder