Search code examples
javacandroid-ndkjava-native-interface

JNI: Native library requires void*, how can I convert my jbytearray to C void*


Here is what I have so far:

Java:

public static native String getConfigName(byte[] array);

C: (the code below returns a dummy value for compilation)

jstring Java_com_example_plugin_HelloJni_getConfigName( JNIEnv* env, jobject thiz, jbyteArray array )
{

    // get jbyte array from array and it's length
    jbyte* bufferPtr = (*env)->GetByteArrayElements(env, array, NULL);
    jsize lengthOfArray = (*env)->GetArrayLength(env, array);

    // Code I need to run using void* and size_t
    dlpspec_scan_read_configuration (   void *  pBuf, const size_t  bufSize )

    // release array
    (*env)->ReleaseByteArrayElements(env, array, bufferPtr, 0);

    return (*env)->NewStringUTF(env, "Hello from JNI !  Compiled with ABI");
}

How can I convert this jbyte* to a void* would it be a simple (void*) cast? also what about the jsize to size_t conversion? this is my first time using JNI and the Android NDK. Thanks


Solution

  • How can I convert this jbyte* to a void* would it be a simple (void*) cast?

    Assuming that you want to pass the data it points to as-is, yes. Or just pass your jbyte* to dlpspec_scan_read_configuration without any casting. Either way it's your responsibility to make sure that it's the correct type of data for dlpspec_scan_read_configuration (e.g. if your function expects a void* to an ASCII string but you pass it a void* to a Unicode string then you probably wouldn't get the desired result).

    what about the jsize to size_t conversion

    jsize is an alias for jint, which is a signed 32-bit integer type. size_t on the other hand is an unsigned integer type of unspecified size. So you should check that your jsize is in the range 0..SIZE_MAX. If it is, you can cast it to a size_t. If it isn't, it's up to you what you want to do (clamp the value, return an error, abort the program, ...).