[英]Getting a null byte array in java from JNI
我正在從 java 調用本機 function 以返回一個字節 []。
以下是 JNI 代碼片段
jbyteArray result;
jbyte *resultType;
result = (*env)->NewByteArray(env, 1);
*resultType =7;
(*env)->SetByteArrayRegion(env, result, 0, 1, resultType);
return result;
這應該創建一個長度為 1 的字節數組,並將值 7 存儲在其中。 我的實際代碼應該創建一個動態長度的數組,但我遇到了與本示例相同的問題。
現在來解決我的問題——在 java 中,從 JNI 返回的數組是 null。 我究竟做錯了什么? 任何幫助將不勝感激。
SetByteArrayRegion()
的原型是:
void SetByteArrayRegion(JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf);
最后一個參數是一個 memory 緩沖區, SetByteArrayRegion()
將從該緩沖區復制到 Java 數組中。
您永遠不會初始化該緩沖區。 你正在做:
jbyte* resultType;
*resultType = 7;
我很驚訝您沒有得到核心轉儲,因為您正在將7
寫入 memory 的某個隨機位置。 相反,請執行以下操作:
jbyte theValue;
theValue = 7;
(*env)->SetByteArrayRegion(env, result, 0, 1, &theValue);
更普遍,
// Have the buffer on the stack, will go away
// automatically when the enclosing scope ends
jbyte resultBuffer[THE_SIZE];
fillTheBuffer(resultBuffer);
(*env)->SetByteArrayRegion(env, result, 0, THE_SIZE, resultBuffer);
或者
// Have the buffer on the stack, need to
// make sure to deallocate it when you're
// done with it.
jbyte* resultBuffer = new jbyte[THE_SIZE];
fillTheBuffer(resultBuffer);
(*env)->SetByteArrayRegion(env, result, 0, THE_SIZE, resultBuffer);
delete [] resultBuffer;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.