我有一個C++ dll,其中包含需要在Java程序中使用的方法。我已經完成了關於JNI的所有Sun文檔以及我在網上找到的大量教程,並且我似乎無法找到與我的代碼相關的問題。實際上,從各種教程和Sun網站上剪下並粘貼了相當一部分代碼。在C++中使用Java Native(JNI)方法在jdoubleArray和向量<double>之間進行轉換
我的具體問題如下:我的C++本地方法從我的Java程序,這需要被映射到然後可傳遞至在C++ DLL的方法的C++矢量接收jdoubleArray。 dll中的方法返回另一個向量,然後需要將其映射到新的jdoubleArray,並返回到Java程序。問題似乎是我沒有正確執行映射。
我的代碼如下(我已經刪除調用爲了簡單的dll法):
JNIEXPORT jdoubleArray JNICALL Java_jniarraypassing_JNIArrayPassing_passAndReturn(JNIEnv *env, jclass jcls, jdoubleArray arr)
{
//First get a pointer to the elements within the jdoubleArray
jsize len = env->GetArrayLength(arr);
jboolean isCopy1;
jdouble *body = env->GetDoubleArrayElements(arr, &isCopy1);
//Create the vector<double> and reserve enough memory for mapping
std::vector<double> newvector;
newvector.reserve(len);
//Copy the contents of the jdoubleArray to the vector<double>
for (int i=0; i<len; i++)
{
newvector.push_back(body[i]);
}
//Release the pointer to the jdoubleArray
if (isCopy1 == JNI_TRUE)
{
env->ReleaseDoubleArrayElements(arr, body, JNI_ABORT);
}
//Call the dll method here....
jdoubleArray output = env->NewDoubleArray(newvector.size());
jboolean isCopy2;
jdouble* destArrayElems = env->GetDoubleArrayElements(output, &isCopy2);
for (int i=0; i<newvector.size(); i++)
{
destArrayElems[i] = newvector[i];
}
if (isCopy2 == JNI_TRUE)
{
env->ReleaseDoubleArrayElements(arr, destArrayElems, 0);
}
return output;
}
當身體的I輸出的內容[I]到控制檯,得到了一個一系列看起來十分像十六進制值的數字(例如003DFBE0),但它們都是一樣的,所以我不認爲它們可以是內存地址。
返回的jdoubleArray的內容完全由默認的double值(即0.0)組成,我懷疑這是因爲原始jdoubleArray的值是無效的?
我需要知道的是,
任何幫助,將不勝感激!
非常感謝,我明白我做錯了什麼!它現在完美運行! –