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

How to convert Arraylist in java to lpwstr in c using jni

本文关键字:中的 转换 lpwstr Arraylist jni java 何使用      更新时间:2023-10-16

我正在使用JNI将ArrayList传递给c++。我想把它转换成LPWSTR*类型。但我收到的是作为工作对象的arraylist。如何转换?

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

你有一个对象。获取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