- OSStatus status = noErr ;
- ByteCount byteOutLen ;
- ByteCount byteInLen = strlen(psz) ;
- wchar_t *tbuf = NULL ;
-
- if (buf == NULL)
- {
- n = byteInLen ;
- tbuf = (wchar_t*) malloc( n * SIZEOF_WCHAR_T) ;
- }
-
- ByteCount byteBufferLen = n * SIZEOF_WCHAR_T ;
- status = TECConvertText(m_MB2WC_converter, (ConstTextPtr) psz , byteInLen, &byteInLen,
- (TextPtr) (buf ? buf : tbuf) , byteBufferLen, &byteOutLen);
-
- if ( buf == NULL )
- free(tbuf) ;
-
- size_t res = byteOutLen / SIZEOF_WCHAR_T ;
+ OSStatus status = noErr ;
+ ByteCount byteOutLen ;
+ ByteCount byteInLen = strlen(psz) ;
+ wchar_t *tbuf = NULL ;
+ UniChar* ubuf = NULL ;
+ size_t res = 0 ;
+
+ if (buf == NULL)
+ {
+ n = byteInLen ;
+ tbuf = (wchar_t*) malloc( n * SIZEOF_WCHAR_T) ;
+ }
+ ByteCount byteBufferLen = n * sizeof( UniChar ) ;
+#if SIZEOF_WCHAR_T == 4
+ ubuf = (UniChar*) malloc( byteBufferLen + 2 ) ;
+#else
+ ubuf = (UniChar*) (buf ? buf : tbuf) ;
+#endif
+ status = TECConvertText(m_MB2WC_converter, (ConstTextPtr) psz , byteInLen, &byteInLen,
+ (TextPtr) ubuf , byteBufferLen, &byteOutLen);
+#if SIZEOF_WCHAR_T == 4
+ // we have to terminate here, because n might be larger for the trailing zero, and if UniChar
+ // is not properly terminated we get random characters at the end
+ ubuf[byteOutLen / sizeof( UniChar ) ] = 0 ;
+ wxMBConvUTF16BE converter ;
+ res = converter.MB2WC( (buf ? buf : tbuf) , (const char*)ubuf , n ) ;
+ free( ubuf ) ;
+#else
+ res = byteOutLen / sizeof( UniChar ) ;
+#endif
+ if ( buf == NULL )
+ free(tbuf) ;
+