Truncated jstring under JRE 1.6 with NewStringUTF
Hi,
I have a JNI app that runs perfectly up to JRE 1.5_07, but crashes on JRE 1.6. After some debugging, I found out the reason for the crash was that the Java UI was received truncated strings from the C++ DLL.
Again, when I run the app with JRE 1.5_07 or earlier, the strings are passed in full. But under JRE 1.6, I can see they are truncated. Did anyone face a similar problem?
I am testing it under Wndows XP. The instruction I use for converting my strings to Unicode is:
jstring jstrTunes = env->NewStringUTF((const char*)GetCompositionsMgr().GetTunes(intPartIndex, ptrRagaString));
Thanks for any help you can provide.
Mariano
[680 byte] By [
swara] at [2007-11-26 17:19:01]

# 1
After further debugging, I have noticed that the resulting jstring was truncated by one character for each "special" character found in the original string (I use "? as a separator). Surprisingly this was never a problem before JRE 1.6.
The solution seems to be to use the MultiByteToWideChar() function in the C++ part. I did that through this function found on these forums:
jstring WindowsTojstring(JNIEnv* pEnv, CONST char* str)
{
jstring rtn = 0;
int slen = strlen(str);
wchar_t* buffer = 0;
if( slen == 0 )
rtn = pEnv->NewStringUTF( str ); //UTF ok since empty string
else
{
int length = MultiByteToWideChar( CP_ACP, 0, (LPCSTR)str, slen, NULL, 0 );
buffer = (unsigned short *)malloc( length*2 + 1 );
if( MultiByteToWideChar( CP_ACP, 0, (LPCSTR)str, slen, (LPWSTR)buffer, length ) >0 )
rtn = pEnv->NewString( (jchar*)buffer, length );
}
if( buffer )
free( buffer );
return rtn;
}
You would then replace:
jstring jstrTunes = env->NewStringUTF((const char*)GetCompositionsMgr().GetTunes(intPartIndex, ptrRagaString));
by:
jstring jstrTunes = WindowsTojstring(env, (const char*)GetCompositionsMgr().GetTunes(intPartIndex, ptrRagaString));
Hope this helps anyone facing the same problem.
Cheers!
Mariano
swara at 2007-7-8 23:47:00 >
