l used ANDROID NDK 。so l want to format something。just use sprintf,but l can not use it with wchar_t. is there some helps for me?
问题:
回答1:
You probably want swprintf and friends, assuming Android has it like Posix and Linux systems.
Glib (from GTK) has functions for unicode manipulation and for string utilities. I believe you should be able to make it work on Android.
回答2:
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);
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 ());
Starting with Android 5.0 ("Lollipop"), sprintf() supports the "%ls" format specifier, so the original sprintf() code above works correctly.
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));
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.