繁体   English   中英

对于Mac OS X下的某些Unicode代码点,vswprintf失败

[英]vswprintf fails for certain unicode codepoints under Mac OS X

我从收到莫名其妙的故障(返回值-1) vswprintf使用GCC和Mac OS X(Mac OS X下用gcc 4.0和4.2.1进行测试10.6和10.8。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;
}

从我的测试看来,根据str的值, vswprintf有时会失败。 例子:

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字符的字符串都将触发此问题。 任何人都可以弄清楚为什么会这样吗? 似乎是一个太大的问题,以前从未注意到过!

如果设置语言环境,就可以了。 要获取环境变量,您可以执行以下操作:

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. 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM