问题描述
我想将 java 类对象传递给 JNI 方法,我想在 JNI 方法中调用几个方法,如下所示.
I'd like to pass java class object to JNI method,And I want to call few methods in JNI method like below.
有人有下面这样的例子吗?
Is there anyone who have some example like below?
class JavaClassParameter{
void javaMethodTobeCalledInJNI(){
...java source...
}
}
class MainJavaClass{
void somemethod(){
JavaClassParameter object = new JavaClassParameter();
JNIMethod(object);
}
native void JNIMethod(JavaClassParameter object);
}
// C++ code
void JNIMethod(object){
object->javaMethodTobeCalledInJNI();
}
推荐答案
你的方法声明:
class MainJavaClass {
native void JNIMethod(JavaClassParameter object);
}
意味着 javah 应该生成一个转发声明如下:
means javah should generate a forward declaration like the following:
JNIEXPORT void JNICALL Java_MainJavaClass_JNIMethod(JNIEnv* env, jobject mainJavaClass);
在实施过程中,您需要做一些事情:
In the implementation of that, you have a few things to do:
使用FindClass
,它接受一个字符串名称:
Use FindClass
, which takes a string name:
jclass cls = env->FindClass("JavaClassParameter");
查找 javaMethodTobeCalledInJNI()
使用GetMethodID
,获取要检查的类、方法的字符串名称及其签名.由于这是一个没有参数的 void 函数,它的 签名 只是 ()V
:
Find javaMethodTobeCalledInJNI()
Use GetMethodID
, which takes the class to check, the string name of the method, and its signature. Since this is a void function with no arguments, its signature is just ()V
:
jmethodID method = env->GetMethodID(cls, "javaMethodTobeCalledInJNI", "()V");
调用 javaMethodTobeCalledInJNI()
使用 CallVoidMethod
,它接受对象实例、方法 ID 和任何参数(在这种情况下没有参数):
Call javaMethodTobeCalledInJNI()
Use CallVoidMethod
, which takes the object instance, the method ID, and any arguments (none in this case):
env->CallVoidMethod(mainJavaClass, method);
您应该在每一步之后检查 NULL 结果;如果你从一个 JNI 函数返回一个 NULL 并将它传递给另一个,你通常会导致 JVM 崩溃
You should check for NULL results after each step; if you get a NULL back from one JNI function and pass it to another, you'll usually crash the JVM
这篇关于如何将java类实例作为参数传递给JNI方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!