簡體   English   中英

如何轉換ArrayList <byte[]> 矢量 <char[]> 對於JNI?

[英]How to convert ArrayList<byte[]> to vector<char[]> for JNI?

我想將java中的ArrayList轉換為c ++中的向量。 我怎樣才能做到這一點?

輸入:c ++中的jobject輸入,它是JAVA中的ArrayList。 輸出:c ++中名為vector的類;

//找到jclass 4 ArrayList,只測試jposCommits和jnegCommits是ArrayList的實例

jclass cls_arraylist = env->FindClass("java/util/ArrayList");

//get element
jmethodID arraylist_get = env->GetMethodID(cls_arraylist, "get", "(I)Ljava/lang/Object;");
//get array size
jmethodID arraylist_size = env->GetMethodID(cls_arraylist,"size","()I");
//get the length of pos and neg commits
jint lenArrayList_byte32 = env->CallIntMethod(jobArrayList_byte32, arraylist_size);


vector<byte[]> retKeyV;

for (int i = 0; i < lenArrayList_byte32; ++i) {

    jobject joneKey = env->CallObjectMethod(jobArrayList_byte32, arraylist_get, i);

我接下來該怎么辦

    jbytearray joneKey = static_cast<jbytearray>(env->CallObjectMethod(jobArrayList_byte32, arraylist_get, i));
    // to be protected, check that the type matches your expectation
    jclass joneKey_class = env->GetObjectClass(joneKey);
    jclass byteArray_class = env->FindClass("[B");
    assert(env->IsInstanceOf(joneKey_class, byteArray_class));
    jlong joneKey_len = env->GetArrayLength(joneKey);
    assert(joneKey_len > 0);
    byte* coneKey = new byte[joneKey_len];
    retKeyV.append(coneKey);
    env->GetByteArrayRegion(joneKey, 0, joneKey_len, coneKey);
    env->DeleteLocalRef(byteArray_class); // see comment below
    env->DeleteLocalRef(joneKey_class);
    env->DeleteLocalRef(joneKey);
}

為了減少一些不必要的開銷,您可以保留對byteArray_class的全局引用,而不必每次都重復FindClass() 如果您不確定輸入數據是否正確,則可以跳過所有IsInstance()檢查。 但是,如果您不檢查數據,請准備崩潰,如果數據不符合您的預期。

創建矢量時,可以retKeyVlenArrayList_byte32容量設置為retKeyV

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM