3

GCC と Mac OS X を使用すると、不可解なエラー (戻り値 -1) が発生します ( vswprintfMac OS X 10.6 および 10.8 で gcc 4.0 および 4.2.1 でテスト済み。Linux での GCC は影響を受けません。Visual Studio も影響を受けません)。

問題を示すために、ここvswprintfの例を最小限に調整して、の戻り値を出力するようにしました。

/* vswprintf example */
#include <stdio.h>
#include <stdarg.h>
#include <wchar.h>

void PrintWide ( const wchar_t * format, ... )
{
    wchar_t buffer[256];
    va_list args;
    va_start ( args, format );
    int res = vswprintf ( buffer, 256, format, args );
    wprintf ( L"result=%d\n", res );
    fputws ( buffer, stdout );
    va_end ( args );
}

int main ()
{
    wchar_t str[] = L"test string has %d wide characters.\n";
    PrintWide ( str, wcslen(str) );
    return 0;
}

私のテストから、 の値によってはstrvswprintf時々失敗するようです。例:

wchar_t str[] = L"test string has %d wide characters.\n"; // works
wchar_t str[] = L"ßß® test string has %d wide characters.\n"; // works
wchar_t str[] = L"日本語 test string has %d wide characters.\n"; // FAILS
wchar_t str[] = L"Π test string has %d wide characters.\n"; // FAILS
wchar_t str[] = L"\u03A0 test string has %d wide characters.\n"; // FAILS

上記の Unicode コードポイントを持つ文字を含む文字列は、0xffこの問題を引き起こすようです。なぜこれが起こっているのか、誰かが光を当てることができますか? これまで気づかなかったほど大きな問題のようです。

4

1 に答える 1

0

ロケールを設定すれば問題ないはずです。環境変数を取得するには、次のようにします。

setlocale(LC_CTYPE, "");   // include <locale.h>

または明示的に設定します。これは、すべての出力関数が使用するエンコーディングを知る必要があるためです。

OS X はvswprintfまったく実行できませんが、Linux はそれを実行します (ただし、印刷すると文字は正しくありません)。

glibc ドキュメントの関連セクションは次のとおりです。

   If  the  format  string contains non-ASCII wide characters, the program
   will only work correctly if the LC_CTYPE category of the current locale
   at  run time is the same as the LC_CTYPE category of the current locale
   at compile time.  This is because the wchar_t representation  is  plat‐
   form-  and  locale-dependent.   (The  glibc  represents wide characters
   using their Unicode (ISO-10646) code point, but other  platforms  don't
   do  this.
于 2013-03-15T19:15:39.963 に答える