Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass char array from C JNI function to Java method as byte[]

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

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?

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

like image 498
hyde Avatar asked Mar 19 '23 10:03

hyde


1 Answers

Below example works for passing char[] from C code to 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));
}
like image 179
Shiv Buyya Avatar answered Apr 25 '23 09:04

Shiv Buyya