JNI函数调用上的ClassCastException:CallVoidMethod
ClassCastException on JNI function call: CallVoidMethod
我正试图在Android应用程序中从本机C++代码中调用一个java方法。当我试图调用我的Java方法时,会发生一个异常。我看了几个例子,但我不明白我做错了什么。请帮帮我。
Java端:
public class UsbAudioRecorder {
private UsbAudioRecordListener listener;
UsbAudioRecorder(UsbAudioRecordListener listener){
this.listener = listener;
}
static {
System.loadLibrary("usbaudio");
}
public native int native_setupConnection(final int fd, final String usbfs_path);
public native void start();
public void received(byte[] audio){
listener.recorded(audio);
}
//some more methods...
}
本地代码:
static jclass class_usbAudioRecorder = NULL;
static jmethodID methId_UsbAudioRecorder_received;
JNIEXPORT jint JNICALL Java_com_example_soundcard_UsbAudioRecorder_native_1setupConnection
(JNIEnv *env , jobject obj, jint fd, jstring usbfs_path){
// Get the objects class
jclass clazz = env->GetObjectClass(obj);
if (!clazz) {
LOGD("Could not find class");
error = LIBUSB_ERROR_OTHER;
}
class_usbAudioRecorder = (jclass) env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
// Get the callbacks method id
methId_UsbAudioRecorder_received = env->GetMethodID(class_usbAudioRecorder,"received", "([B)V");
if (!methId_UsbAudioRecorder_received) {
LOGD("Could not find method");
env->DeleteGlobalRef((jobject) class_usbAudioRecorder);
error = LIBUSB_ERROR_OTHER;
goto err;
}
// event handle callback
static void cb_trans(struct libusb_transfer* transfer){
// Create a jbyteArray.
jbyteArray audioArray = env->NewByteArray(PACKET_SIZE * transfer->num_iso_packets);
//here i populate jbyteArray with data
// Callback
env->CallVoidMethod(class_usbAudioRecorder, methId_UsbAudioRecorder_received, audioArray);
// cleaning up
env->DeleteLocalRef(audioArray);
jthrowable exc;
exc = env->ExceptionOccurred();
if (exc) {
env->ExceptionDescribe();
}
if (env->ExceptionCheck()) {
LOGD("Exception while trying to pass sound data to java");
env->ExceptionClear();
return;
}
异常输出:
10-27 15:19:55.658 11890-12476/com.example.soundcard W/系统错误:java.lang.ClassCastException:[B不能强制转换为com.example.soundcard.UsbAudioRecorder 10-27 15:19:55.65811890-12476/com.example.soundcard W/系统错误:位于java.lang.Class.cast(Class.java:1278)10-27 15:19:55.66311890-12476/com.example.soundcard W/系统错误:位于com.example.soundcard.UsbAudioRecorder.start(本地方法)10-2715:19:55.663 11890-12476/com.example.soundcard W/System.err:在com.example.soundcard.MainActivity$OnClickListener$1.run(MainActivity.java:279)10-27 15:19:55.663 11890-12476/com.example.soundcard W/系统错误:
在java.lang.Thread.run(Thread.java:841)
我找到了解决方案。只是为了节省一些时间:调用非静态方法时,需要将类实例作为jobject
传递给CallVoidMethod
。我的错误是用jclass
调用它,它只适用于静态方法。