Nick
Nick

Reputation: 3435

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?

Upvotes: 0

Views: 946

Answers (2)

weston
weston

Reputation: 54781

Have you looked at jbyteArray or jintarray? I use that for processing YuV to RGB on native side although I'm passing the byte[] from java to c should work your way too.

Upvotes: 0

Samhain
Samhain

Reputation: 1765

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

Upvotes: 1

Related Questions