Sirop4ik
Sirop4ik

Reputation: 5273

How to invoke specific Java method from NDK(JNI)?

I am fresh in this topic.

I use NDK in my Android app and I have such method in Java

static byte[] getBytes(Bitmap bitmap)
{
    int size = bitmap.getRowBytes() * bitmap.getHeight();
    ByteBuffer byteBuffer = ByteBuffer.allocate(size);
    bitmap.copyPixelsToBuffer(byteBuffer);
    return byteBuffer.array();
}

Now I need to use this method from NDK

Actually I wrote something like this

jbyteArray arr = env->CallStaticByteMethod(jniIds.helper_class, jniIds.get_bytes, image_obj);

But problem is CallStaticByteMethod return type jbyte, but I need jbyteArray...

So, question how to write this method?

EDIT

jobject arr_obj = env->CallStaticObjectMethod(jniIds.helper_class, jniIds.get_bytes, image_obj);
jbyteArray arr = static_cast<jbyteArray>(arr_obj);

//my needed result
unsigned char myArr = reinterpret_cast<unsigned char>(arr);

EDIT

jbyteArray arr_obj = (jbyteArray) env->CallStaticObjectMethod(jniIds.helper_class, jniIds.get_bytes, image_obj);

Now I have jbyteArray... but anyway I don't understand how with using of GetByteArrayElements get my byte[] into my var unsigned char *i_image?

EDIT

jbyteArray arr_obj = (jbyteArray)env->CallStaticObjectMethod(jniIds.helper_class, jniIds.get_bytes, image_obj);
jbyte *b = (jbyte *) env->GetByteArrayElements(arr_obj, NULL);
i_image = reinterpret_cast<unsigned char *>(b);
env->ReleaseByteArrayElements(arr_obj, b, JNI_ABORT);

Upvotes: 0

Views: 549

Answers (1)

Botje
Botje

Reputation: 31193

As per the JNI specification, byte arrays are not primitive types, they are objects. As such, you need to use CallStaticObjectMethod.

The result type will be jobject, but you can safely cast this to jbyteArray (if it is not null, of course). With the jbyteArray in hand you can call GetByteArrayElements or GetByteArrayRegion.

Upvotes: 1

Related Questions