Android JNI-将jstring转换为wchar_t的可靠方法 [英] Android JNI - Reliable way to convert jstring to wchar_t

查看:297
本文介绍了Android JNI-将jstring转换为wchar_t的可靠方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Android JNI代码中,我需要将jstring转换为wchar_t.我找到的最接近的参考是如何将jstring转换为wchar_t * .

In my Android JNI code, I need to convert jstring to wchar_t. The closest reference I found was How do I convert jstring to wchar_t *.

可以使用以下代码获取jchar *和长度:

One can obtain jchar* and the length using the following code:

const jchar *raw = env->GetStringChars(string, 0);
jsize len = env->GetStringLength(string);

wchar_t* wStr = new wchar_t[len+1];

似乎我无法使用wcncpy将原始"复制到"wStr".尽管jchar的长度为2个字节,但在所有现代版本的Android OS中,wchar_t的长度均为4个字节.

It seems I cannot use wcncpy to copy "raw" into "wStr." Although jchar is 2-bytes long, wchar_t is 4 bytes long on all modern versions of Android OS.

一个选项是在for循环中一次复制一个字符:

One option is to copy one character at a time in a for loop:

for(int i=0;i<len;i++) {
    wStr[i] = raw[i];
}
wStr[len] = 0;

另一种选择是调用env-> GetStringUTFChars()并使用iconv_ *例程转换为wchar_t类型.

The other option would be to call env->GetStringUTFChars() and use iconv_* routines to convert to wchar_t type.

有人可以确认选项1是否有效?希望我不必求助于选项2.有没有更好的选择?问候.

Can someone please confirm if option 1 is valid? Hope I don't have to resort to option 2. Is there a better option? Regards.

推荐答案

只要您的所有数据都是UCS2,就可以使用选项1 .请参阅 wchar_t(适用于Linux上的UTF-16)? 进行类似的讨论.请注意,C ++ 11提供了 std :: codecvt_utf16 来处理这种情况

As long as all your data is UCS2, you can use option 1. Please see wchar_t for UTF-16 on Linux? for a similar discussion. Note that C++11 provides std::codecvt_utf16 to deal with the situation.

这篇关于Android JNI-将jstring转换为wchar_t的可靠方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆