gpt4 book ai didi

Java JNI GetMethodID 返回 NULL

转载 作者:太空狗 更新时间:2023-10-29 13:28:22 24 4
gpt4 key购买 nike

我在 Java 中有这个类:

public class CameraActivity extends Activity {

...

public class RecognitionResult {
public String text;
public int x;
public int y;
public int width;
public int height;

public RecognitionResult(String text, int x, int y, int width, int height) {
this.text = text;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
}

这是我的 JNI 代码:

extern "C"
jobject Java_com_example_parkingcontrolsystem_CameraActivity_recognizeNumberPlate(JNIEnv *env,
jobject object,
jstring filename)
{
jclass cls = env->FindClass("com/example/parkingcontrolsystem/CameraActivity$RecognitionResult");
std::cout << "Class: " << cls << std::endl;

jmethodID constructor = env->GetMethodID(cls, "<init>", "(Ljava/lang/String;IIII)V");
std::cout << "Method: " << constructor << std::endl;

recognition_result = env->NewObject(cls, constructor, "Hello from JNI", 0, 0, 50, 100);
std::cout << "Object: " << recognition_result << std::endl;

return recognition_result;
}

FindClass 返回的不是 NULL,好的。但是 GetMethodID 总是返回零。我尝试创建不带参数的默认构造函数,而不是使用“()V”签名,但 GetMethodID 返回 NULL。

怎么了?

最佳答案

如果使用 JNI 实例化内部类,则还必须在与 GetMethodId 一起使用的签名中传递父类,以便接收有效的 jmethodID

假设 BA 的内部类,并且有一个构造函数,如:public B(int someint) 下面的代码可以工作( jobj 指向 A 的实例):

jclass jclazz = env->FindClass("org/somepackage/A$B");
assert(jclazz != nullptr);
jmethodID mid = env->GetMethodID(jclazz, "<init>", "(Lorg/somepackage/A;I)V");
assert(mid != nullptr);
env->NewObject(jclazz, mid, jobj, 1);

ops 问题的解决方案是:

 jclass cls = env->FindClass("com/example/parkingcontrolsystem/CameraActivity$RecognitionResult");
std::cout << "Class: " << cls << std::endl;
jmethodID constructor = env->GetMethodID(cls, "<init>","Lcom/example/parkingcontrolsystem/CameraActivity;Ljava/lang/String;IIII)V");
std::cout << "Method: " << constructor << std::endl;
recognition_result = env->NewObject(cls, constructor, object, "Hello from JNI", 0, 0, 50, 100);
std::cout << "Object: " << recognition_result << std::endl;

注意:Selven 在评论中也发布了相同的答案但没有发布答案。

关于Java JNI GetMethodID 返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19004631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com