如何从C JNI函数传递char数组到Java方法的byte []

如何从C JNI函数传递char数组到Java方法的byte []

问题描述:

我无法找到合适的文档从JNI方法传递一个字符缓冲区到Java方法。这里的code

I'm having trouble finding the right documentation for passing a char buffer from JNI method to Java method. Here's the code

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 右功能用在这里,有什么要传递给它,如何分配,以及如何(如果有的话)应该被释放正确的事?

Is CallVoidMethod the right function to use here, what's the correct thing to pass to it, how to allocate it, and how (if at all) it should be freed?

一个code片段很可能是最紧凑的答案,用几句话解释对象的所有权如何。

A code snippet would probably be the most compact answer, with a few words explaining how ownership of objects goes.

您正在寻找的功能是GetByteArrayElements和ReleaseByteArrayElements。

The functions you are looking for are GetByteArrayElements and ReleaseByteArrayElements.

这样的事情应该做的伎俩:

Something like this should do the trick:

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;
}