Way to pass byte[] as char* from Android to C++
-
I am developing an Android app using Qt. The app is communicating with a FTDI device via Android's USB libraries. The device sends me hex data which is stored in byte[] array on the android side. The approaches i stumbled upon require converting it to String before passing it to c++. Unfortunately this conversion ruins my hex data due to using UTF-8. So i am wandering if there is a way that could let me pass byte[] from Java and it to appear as char* in the c++ side?
Going from:
private static native void getData(String message);
JNINativeMethod methods[] { {"getData", "(Ljava/lang/String;)V", reinterpret_cast<void *>(getData)} };
static void getData(JNIEnv *env, jobject /*thiz*/, jstring value)
to something like:
private static native void getData(byte[] message);
JNINativeMethod methods[] { {"getData", "([B)V", reinterpret_cast<void *>(getData)} };
static void getData(JNIEnv *env, jobject /*thiz*/, jbyteArray value)
Can anyone prompt me with some ideas?
-
@Kyeiv said in Way to pass byte[] as char* from Android to C++:
i corrected it, but can you answer the question? how to cature this jbyteArray as char*
Yes I can ;)
void getData(JNIEnv *env, jobject /*thiz*/, jbyteArray value) { // get array pointer and size jbyte *bytes = env->GetByteArrayElements(value, false); int arrayLength = env->GetArrayLength(value); // copy to local variable, for example a QByteArray QByteArray b = QByteArray::fromRawData((const char*)bytes , arrayLength); // release memory env->ReleaseByteArrayElements(value, bytes, JNI_ABORT); }
-
@Kyeiv said in Way to pass byte[] as char* from Android to C++:
Can anyone prompt me with some ideas?
You function has wrong signature:
static void getData(JNIEnv *env, jobject /*thiz*/, jbyte value)
should be:
static void getData(JNIEnv *env, jobject /*thiz*/, jbyteArray value)
cf. https://doc.qt.io/qt-5/qandroidjniobject.html#object-types
-
@Kyeiv said in Way to pass byte[] as char* from Android to C++:
i corrected it, but can you answer the question? how to cature this jbyteArray as char*
Yes I can ;)
void getData(JNIEnv *env, jobject /*thiz*/, jbyteArray value) { // get array pointer and size jbyte *bytes = env->GetByteArrayElements(value, false); int arrayLength = env->GetArrayLength(value); // copy to local variable, for example a QByteArray QByteArray b = QByteArray::fromRawData((const char*)bytes , arrayLength); // release memory env->ReleaseByteArrayElements(value, bytes, JNI_ABORT); }