Sam Er
Sam Er

Reputation: 33

An error occurred while calling the java function from jni

I want to access the java function(transceive) from JNI. I get message error unfortunately, app has stopped when call transceive function from IsoDep.java

How to call transceive function when parameters and output in the form of an bytes array?

Please help me, thanks.

JMain.java

Class JMain {
    static {
        System.loadLibrary("Native");
    }

    public native byte[] ReadData();
}

IsoDep.java

public byte[] transceive(byte[] data) throws IOException {
    //
}

Native.cpp

#include <jni.h>
#include <iostream>

#ifdef __cplusplus
    extern "C" {
#endif

JNIEnv *JNI_GetEnv() {
   //
}

JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM *jvm, void *reserved) {
     //
}


jbyteArray SendReq(jobject isoDep, jbyteArray b) {
    // PROBLEM IN HERE..
    //   Error unfortunately, app has stopped when call transceive function
    //   from IsoDep.java
    jbyte *args = e->GetByteArrayElements(b, NULL); 
    return (jbyteArray) e->CallObjectMethodA(isoDep, _midTransceive, (jvalue *) args);  
}

JNIEXPORT jbyteArray JNICALL
Java_com_company_appname_JMain_ReadData(JNIEnv *env, jobject obj) {
    //
}

#ifdef __cplusplus
    }
#endif

Upvotes: 0

Views: 370

Answers (1)

user2543253
user2543253

Reputation: 2173

Your transceive method wants a Java byte array reference (jbyteArray/jobject) as a parameter, not a C++ jbyte pointer (jbyte*).

When you extraxt the byte array's contents with GetByteArrayElements you get something that is only usable in the native code and not a valid Java reference (and passing that non-reference to a Java method is what makes your program crash). Omit that step and pass b directly.

Upvotes: 1

Related Questions