java - 如何使用jni将java中的Arraylist转换为c中的lpwstr

标签 java c++ arraylist java-native-interface

我正在使用 JNI 将 ArrayList 传递给 C++。我想将其转换为 LPWSTR* 类型。但我收到数组列表作为 jobobject。我该如何转换它?

最佳答案

让我们开始吧。我不确定其中的一些转换,希望其他人能提供帮助。

你有一个对象。获取 JNI 的方法并调用它们。很简单。

以下代码示例可能有助于入门。

// parameter
jobject YourJObjectRepresentingArrayList;

// I suppose you have the JNIEnv somehow
JNIEnv* env;

// use the Array list
ArrayList_class       = env->FindClass( "java/util/ArrayList" );

    // to conver jobject to jstring
    jmethodID caster = env->GetMethodID(ArrayList_class, "toString", "()Ljava/lang/String;");

// get two methods
Get_method            = env->GetMethodID( ArrayList_class, "get", "(I)Ljava/lang/Object" );
Size_method           = env->GetMethodID( ArrayList_class, "size", "()I" );

// call java.lang.ArrayList.get()
int NumElts = env->CallIntMethod(YourJObjectRepresentingArrayList, ArrayList_class, Size_method);

// allocate output array
LPWSTR* Out = new LPWSTR[NumElts];

// fetch all the items
for(int i = 0 ; i < NumElts ; i++)
{
    // call java.lang.ArrayList.get(int index) method
    // Not sure about the parameter passing here
    jobject Tmp = env->CallObjectMethod(YourJObjectRepresentingArrayList, Get_method, i);

    jstring Str = (jstring)env->CallObjectMethod(Tmp, caster);

    // get the length
    int StrLen = env->GetStringLength(env, Str);

    Out[i] = new wchar_t[StrLen];

    const char* SourceUTF = env->GetStringChars(env, Str);

    // store the string - not sure about UTF-16/UTF-8 here. It is OS-dependant.
    // MultiByteToWideChar or iconv on POSIX
    ConvertUTF8ToWChar(Out[i], SourceUTF);

    env->ReleaseStringUTFChars(s, SourceUTF);
}

// done

关于java - 如何使用jni将java中的Arraylist转换为c中的lpwstr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11665495/

相关文章:

java - JSON文件处理错误: A JSONArray text must start with '[' at 1 [character 2 line 1] when use file in UTF-8 encoding

java - 如何用java编写监控软件

c++ - 使用 OpenCV 跟踪手

java - 如何在java selenium中对两个数组字符串值求和并存储到另一个数组列表中?

java - Java中如何访问ArrayList中存储的值?

java - Eclipse中多模块maven web项目的依赖问题

java - 如何使用 itext7 Java 将多个图像添加到 PDF 中?

c++ - C++中通过函数调用创建对象

c++ - alpha 混合后获取像素颜色

java - 如何使用BulkRequest将ArrayList发送到ElasticSearch中?