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:
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.
If we are not interested in cross platform-ability, in windows you can use the MultiByteToWideChar function, or the helpful macros A2W (ref. example).
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...
Just use env->GetStringChars(myString, 0); Java pass Unicode by it's nature