问题描述
我在这个话题上很新鲜.
I am fresh in this topic.
我在Android应用程序中使用NDK,而在Java中也有这种方法
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();
}
现在我需要从NDK使用此方法
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);
但是问题是CallStaticByteMethod
返回类型jbyte
,但是我需要jbyteArray
...
But problem is CallStaticByteMethod
return type jbyte
, but I need jbyteArray
...
那么,问如何编写此方法?
So, question how to write this method?
编辑
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);
编辑
jbyteArray arr_obj = (jbyteArray) env->CallStaticObjectMethod(jniIds.helper_class, jniIds.get_bytes, image_obj);
现在我有jbyteArray ...但无论如何我不明白如何使用GetByteArrayElements
将我的byte[]
放入我的var unsigned char *i_image
中?
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
?
编辑
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);
推荐答案
根据 JNI规范,字节数组不是原始类型,而是对象.因此,您需要使用CallStaticObjectMethod
.
As per the JNI specification, byte arrays are not primitive types, they are objects.As such, you need to use CallStaticObjectMethod
.
结果类型将为jobject
,但是您可以安全地将其强制转换为jbyteArray
(当然,如果不是null
).手持jbyteArray
可以调用GetByteArrayElements
或GetByteArrayRegion
.
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
.
这篇关于如何从NDK(JNI)调用特定的Java方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!