我正在使用 JNI 将对象从 C++ 传递到 Java。但是我卡在了代码中的某个地方 “GetMethodID”总是返回 NULL 并崩溃!下面是我使用的头文件和后面的cpp代码。
My intention is to return an object from the JNI, Where I always get "emu_response_constructor Null" in the below cpp code.
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_em_Grabber */
#ifndef _Included_com_em_Grabber
#define _Included_com_em_Grabber
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_em_Grabber
* Method: getProcessedImage
* Signature: (II[B)Lcom/em/Response;
*/
JNIEXPORT jobject JNICALL Java_com_em_Grabber_getProcessedImage
(JNIEnv *, jobject, jint, jint, jbyteArray);
#ifdef __cplusplus
}
#endif
#endif
下面是我使用的cpp文件。对象被传递给 Java 的地方。
JNIEXPORT jobject JNICALL Java_com_em_Grabber_getProcessedImage
( JNIEnv *env, jobject obj, jint jRows, jint jCols,jbyteArray jByteArray ){
jclass emu_response = env->FindClass("com/em/Response");
if (emu_response == NULL) {
cout << "emu_response Null" << endl;
}
jmethodID emu_response_constructor = env -> GetMethodID(emu_response, "<init>", "(II[B)Lcom/em/Response;");
if (NULL == emu_response_constructor ) {
cout << "emu_response_constructor Null" << endl;
}
int number = 90;
jobject jEmuResponse = env->NewObject ( emu_response,emu_response_constructor, jByteArray, number );
return jEmuResponse;
}
下面是我的java类:
public class Response {
private int age;
private byte[] result = null;
public Response()
{
}
public Response(byte[] result,int age) {
this.age = age;
this.result = result;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public byte[] getResult() {
return result;
}
public void setResult(byte[] result) {
this.result = result;
}
最佳答案
不要尝试自己编写 JNI 签名。使用 javap -s 的输出。
在这种情况下,很明显您的参数类型乱序了。 我认为正确的签名是“([BI)Lcom/em/Response;”,但不要相信我的话:使用 javap -s。总是。
并修复您的代码,这样如果您确实从任何 API 获得了意外结果,您就不会打印它并继续,就好像该值是合法的一样。这就是导致崩溃的原因。
关于java - 在 JNI 中传递对象总是返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16912414/