我无法找到将char缓冲区从JNI方法传递到Java方法的正确文档。这是代码
jint JNICALL Java_foo_package_MyJavaClass_myNativeMethod(JNIEnv *jenv, jobject jobj)
{
jclass clazz = (*jenv)->GetObjectClass(jenv, jobj);
// MyJavaClass method: private void addData(byte[] data)
jmethodID mid = (*jenv)->GetMethodID(jenv, clazz, "addData", "([B)V");
assert(mid);
const char buf[] = { 0, 1, 2, 3, 42 };
const size_t buf_len = sizeof buf;
(*jenv)->CallVoidMethod(jenv, jobj, mid, buf /* obviously wrong */ );
return 0;
}
CallVoidMethod
是否在这里使用正确的函数,传递给它的正确方法是什么,如何分配它,以及如何(如果有的话)它应该被释放?
代码片段可能是最紧凑的答案,只需几句话就可以解释对象的所有权。
答案 0 :(得分:3)
您正在寻找的功能是GetByteArrayElements和ReleaseByteArrayElements。
这样的事情可以解决问题:
jint JNICALL Java_foo_package_MyJavaClass_myNativeMethod(JNIEnv *jenv, jobject jobj)
{
jclass clazz = (*jenv)->GetObjectClass(jenv, jobj);
// MyJavaClass method: private void addData(byte[] data)
jmethodID mid = (*jenv)->GetMethodID(jenv, clazz, "addData", "([B)V");
assert(mid);
const char buf[] = { 0, 1, 2, 3, 42 };
const size_t buf_len = sizeof buf;
jboolean isCopy;
jbyte *jbuf = (*jenv)->GetByteArrayElements(jenv, buf, &isCopy);
(*jenv)->CallVoidMethod(jenv, jobj, mid, jbuf);
(*jenv)->ReleaseByteArrayElements(jenv, buf, jbuf, 0);
return JNI_OK;
}
答案 1 :(得分:2)
下面的示例适用于将char []从C代码传递到Java byte []。
void JNICALL Java_com_example_testapplication_MainActivity_getJNIByteArrayArg(JNIEnv *jenv, jobject jobj)
{
jclass clazz = (*jenv)->FindClass(jenv, "com/example/testapplication/MainActivity"); // class path
jmethodID mid = (*jenv)->GetMethodID(jenv, clazz, "addData", "([B)V");// function name
jbyteArray retArray;
char data[] = {'a','b',3,4,5};
int data_size = 5;
if(!retArray)
retArray = (*jenv)->NewByteArray(jenv, data_size);
if((*jenv)->GetArrayLength(jenv, retArray) != data_size)
{
(*jenv)->DeleteLocalRef(jenv, retArray);
retArray = (*jenv)->NewByteArray(jenv, data_size);
}
void *temp = (*jenv)->GetPrimitiveArrayCritical(jenv, (jarray)retArray, 0);
memcpy(temp, data, data_size);
(*jenv)->ReleasePrimitiveArrayCritical(jenv, retArray, temp, 0);
(*jenv)->CallVoidMethod(jenv, jobj, mid, retArray);
}
public void addData(byte[] data) {
System.out.println("Buyya: From C: " + new String(data));
}