Search code examples
javaandroidcjava-native-interface

How to use direct ByteBuffer


I need to pass a data buffer from C to Java over JNI. So have created a direct ByteBuffer in C and sent it to Java:

void *myBuffer = ...;
int w = ..., h = ...;

jmethodID func = ...;
jobject directBuffer = jni_env->NewDirectByteBuffer(myBuffer, w * h);
jni_env->CallVoidMethod(myActivity, func, directBuffer, w, h);

On Java side I received that buffer succesfully, but I cannot use it!

public static final void Func(final java.nio.ByteBuffer pixels, int w, int h) {
    boolean ok = pixels.hasArray();
    if (ok)
    {
        java.nio.IntBuffer i_pixels = pixels.asIntBuffer();
        final int[] apixels = i_pixels.array();
        Bitmap bm = Bitmap.createBitmap(apixels, w, h, Bitmap.Config.ARGB_8888);
    }
    // ...
}

The first line (boolean ok = pixels.hasArray();) just crashes with UnsupportedOperationException.

As you can see, I need to convert the buffer received into int[] in order to pass it to Bitmap.createBitmap. What am I doing wrong and how to achieve what I need?


Solution

  • Because its a native managed array, you need to access it via the get functions, like getInt()

    SEE: https://groups.google.com/forum/#!topic/android-ndk/yNXuiQkGXPY