先日プログラムを開発しているときに、ASCII 文字列を Unicode 文字列に変換する必要がありました。ところで、私は Visual Studio 2012 を使用して Windows で作業しています。Win32 関数で奇妙な動作に気付きましたが、これは解決MultiByteToWideChar
できませんでした。以下にいくつかのテストコードを書きました。
int main()
{
/* Create const test string */
char str[] = "test string";
/* Create empty wchar_t buffer to hold Unicode form of above string, and initialize (zero) it */
wchar_t *buffer = (wchar_t*) LocalAlloc(LMEM_ZEROINIT, sizeof(wchar_t) * strlen(str));
/* Convert str to Unicode and store in buffer */
int result = MultiByteToWideChar(CP_UTF8, NULL, str, strlen(str), buffer, strlen(str));
if (result == 0)
printf("GetLastError result: %d\n", GetLastError());
/* Print MultiByteToWideChar result, str's length, and buffer's length */
printf_s(
"MultiByteToWideChar result: %d\n"
"'str' length: %d\n"
"'buffer' length: %d\n",
result, strlen(str), wcslen(buffer));
/* Create a message box to display the Unicode string */
MessageBoxW(NULL, buffer, L"'buffer' contents", MB_OK);
/* Also write buffer to file, raw */
FILE *stream = NULL;
fopen_s(&stream, "c:\\test.dat", "wb");
fwrite(buffer, sizeof(wchar_t), wcslen(buffer), stream);
fclose(stream);
return 0;
}
ご覧のとおり、通常の文字列を取得し、Unicode 文字列を格納するためのバッファーを作成し、変換された Unicode 文字列をバッファーに入れ、いくつかの結果を表示し、バッファーをファイルに書き込みます。
出力:
MultiByteToWideChar result: 11
'str' length: 11
'buffer' length: 16
もう変。関数は C 文字列の正しい数の文字を処理していますがwcslen
、出力バッファが C 文字列よりも長いと報告しています! 私もバッファを正しく割り当てたと確信しています。
さまざまなサイズの文字列の長さを使用してみましたが、最後には常にがらくたがあり、wcslen
常にバッファーの長さが 4 の倍数であると報告されます。
最後に、この特定の文字列 ( "test string"
) について、ファイルに出力された生のバッファを次に示します。
74 00 65 00 73 00 74 00 20 00 73 00 74 00 72 00 t.e.s.t. .s.t.r.
69 00 6E 00 67 00 AB AB AB AB AB AB AB AB EE FE i.n.g...........
(これは 32 バイト、つまり 16 の Unicode 文字です。)
最後の 10 バイトは 5 文字です。4 つのU+ABABと 1 つのU+FEEEは、私には意味がありません。
文字列を変換しようとするたびに、さまざまな量で発生します。
私はちょっとアイデアがありません。誰?
前もって感謝します!