I am an Android developer and new to JNI thing - what I'm trying to do is pass a byte array from c++ method to java method. Here is what my c++ method looks like:
void func(char* bytes)
{
jclass callbackClass = fJNIEnv->GetObjectClass(fJObject);
jmethodID javaFunc = fJNIEnv->GetMethodID(callbackClass, "javaFunc", "([B)V");
jbyteArray array = fJNIEnv->NewByteArray(sizeof(bytes));
fJNIEnv->SetByteArrayRegion(array, 0, sizeof(bytes), (jbyte *) bytes);
fJNIEnv->CallNonvirtualVoidMethod(fJObject, callbackClass, javaFunc, array);
}
and here is the javaFunc method:
public void javaFunc(byte[] bytes) {
...
}
when I'm debugging the func method, bytes is pointing to an array of chars, but when I get to the javaFunc method, bytes is something like {16, 0, 0, 0} - it's nothing like what it has to be. Any help would be appreciated.
sizeof(bytes)is wrong. That gives you the byte size of thechar*pointer itself (4 in 32bit, 8 in 64bit), NOT the byte size of the data that is being pointed to. You need to changefunc()to pass the number ofcharsin the array, ievoid func(char* bytes, int numBytes), or pass in a more appropriate container, likestd::vector<char>, iefunc(const std::vector<char> &bytes). Then, you can use the real byte count when allocating and filling the JNI arrayCallNonvirtualVoidMethod()exits, iefJNIEnv->DeleteLocalRef(array);.