问题描述
我用了ANDROID NDK.所以我想格式化一些东西.只用sprintf,但是我不能用wchar_t.对我有帮助吗?
l used ANDROID NDK 。so l want to format something。just use sprintf,but l can not use it withwchar_t. is there some helps for me?
推荐答案
在Android OS NDK 5.0之前的版本("Lollipop")中,sprintf()不支持%ls"(wchar_t指针)格式说明符.因此,以下语句可以编译,但在NDK(5.0之前的版本)下不能正确执行:
In Android OS NDK versions before 5.0 ("Lollipop"), the sprintf() does not support the "%ls" (wchar_t pointer) format specifier. Thus, the following statement compiles but does not execute correctly under NDK (pre-5.0):
char buffer [1000];
wchar_t *wp = L"wide-char text";
sprintf (buffer, "My string is: %ls", wp);
解决方法是使用任何一种开源的Wide-to-utf8实现(例如, UTF8-CPP项目),将其指针传递给sprintf:
The workaround is to convert the wchar_t string to UTF-8 (which is a char *) using any one of the Open Source wide-to-utf8 implementations (e.g. the UTF8-CPP project), passing its pointer to sprintf:
// WcharToUtf8: A cross-platform function I use for converting wchar_t string
// to UTF-8, based on the UTF8-CPP Open Source project
bool WcharToUtf8 (std::string &dest, const wchar_t *src, size_t srcSize)
{
bool ret = true;
dest.clear ();
size_t wideSize = sizeof (wchar_t);
if (wideSize == 2)
{
utf8::utf16to8 (src, src + srcSize, back_inserter (dest));
}
else if (wideSize == 4)
{
utf8::utf32to8 (src, src + srcSize, back_inserter (dest));
}
else
{
// sizeof (wchar_t) is not 2 or 4 (does it equal one?)! We didn't
// expect this and need to write code to handle the case.
ret = false;
}
return ret;
}
...
char buffer [1000];
wchar_t wp = L"wide-char text";
std::string utf8;
WcharToUtf8 (utf8, wp, wcslen (wp));
sprintf (buffer, "My string is: %s", utf8.c_str ());
从Android 5.0(棒棒糖")开始,sprintf()支持%ls"格式说明符,因此上面的原始sprintf()代码可以正常工作.
Starting with Android 5.0 ("Lollipop"), sprintf() supports the "%ls" format specifier, so the original sprintf() code above works correctly.
如果您的Android NDK代码需要在所有版本的Android上运行,则应使用以下宏包装传递给sprintf的所有wchar_t指针:
If your Android NDK code needs to run on all version of Android, you should wrap all your wchar_t pointers passed to sprintf with a macro like the following:
#define CONVERTFORANDROID(e) (GetSupportsSprintfWideChar () ? (void *) e : (void *) WcharToUtf8(e).c_str ())
char buffer [1000];
wchar_t *wp = L"wide-char text";
sprintf (buffer, "My string is: %ls", CONVERTFORANDROID(wp));
GetSupportsSprintfWideChar()函数应为本地函数,如果运行的Android操作系统为5.0或更高版本,则返回true;如果操作系统为5.0之前的版本,则返回false.
The GetSupportsSprintfWideChar() function should be a local function that returns true if the running Android OS is 5.0 or above, while returning false if the OS is pre-5.0.
这篇关于实现函数如何作为sprintf使用wchar作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!