0

我用过ANDROID NDK。所以我想格式化一些东西。只用sprintf,但我不能用它和wchar_t。对我有帮助吗?</p>

4

2 回答 2

1

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.

于 2014-10-23T03:11:54.900 回答
1

你可能想要swprintf和朋友,假设 Android 有它像 Posix 和 Linux 系统。

Glib(来自GTK)具有unicode 操作字符串实用程序的功能。我相信您应该能够使其在Android上运行。

于 2012-06-21T11:10:18.270 回答