我构建了一个如下所示的简单方法
wchar_t buf[1024] = {};
void logDebugInfo(wchar_t* fmt, ...)
{
va_list args;
va_start(args, fmt);
vswprintf( buf, sizeof(buf), fmt, args);
va_end(args);
}
jstring Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
jobject thiz )
{
logDebugInfo(L"test %s, %d..", L"integer", 10);
return (*env)->NewStringUTF(env, buf);
}
我收到以下警告
In function 'Java_com_example_hellojni_HelloJni_stringFromJNI':
warning: passing argument 1 of 'logDebugInfo' from incompatible pointer type
note: expected 'wchar_t *' but argument is of type 'unsigned int *'
结果字符串不正确。 如果我在那个格式化字符串之前删除了那个 L 前缀,奇怪的是,它起作用了。但是在我的遗留代码中到处都使用了 L 前缀。
首先,我知道 wchar_t 的可移植性不够好,而且是特定于编译器的。我预期的 wchar_t 的大小应该是 16 位。我读了一些其他帖子说它是 32 位的 android 但 wchar.h,由官方 NDK 提供,它说 wchar_t == char,真的吗?
最佳答案
来自 NDK r5b 文档/STANDALONE-TOOLCHAIN.html:
5.2/ wchar_t support: - - - - - - - - - - - As documented, the Android platform did not really support wchar_t until Android 2.3. What this means in practical terms is that: - If you target platform android-9 or higher, the size of wchar_t is 4 bytes, and most wide-char functions are available in the C library (with the exception of multi-byte encoding/decoding functions and wsprintf/wsscanf). - If you target any prior API level, the size of wchar_t will be 1 byte and none of the wide-char functions will work anyway. We recommend any developer to get rid of any dependencies on the wchar_t type and switch to better representations. The support provided in Android is only there to help you migrate existing code.
因为你的目标是 Android 1.6,所以看起来 wchar_t 不适合你。
即使在 Android 2.3 平台(“android-9”)中,许多地方仍然有注释,包括 wchar.h
,这意味着 wchar_t
是一个字节,并且没有实现任何宽字符库函数。这表明实现可能仍然不可靠,因此我对在任何 Android 版本上使用 wchar_t 会非常谨慎。
如果您正在寻找替代品,我找到了 UTFCPP成为一个优秀且非常轻量级的库。
关于android - Android真的没有wchar_t吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5630255/