如何从C JNI函数传递char数组到Java方法的byte [] [英] How to pass char array from C JNI function to Java method as byte[]

查看:256
本文介绍了如何从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;
}

这篇关于如何从C JNI函数传递char数组到Java方法的byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆