mgd*_*mgd 2 c++ java java-native-interface osgi
在C/C++中,您需要一个jclass
值,以便使用声明的方法将本机函数注册到Java类native
.
考虑这个Java类:
public class Native {
public native int f(int i);
}
Run Code Online (Sandbox Code Playgroud)
要注册本机C/C++函数,Native.f()
我们需要在C++端调用它:
JNIEnv* env = ...;
jclass nativeClass = ...;
JNINativeMethod nativeMethod = {
(char*) "f",
(char*) "(I)I",
(void*) Java_org_example_Native_f // The native C function
};
env->RegisterNatives(nativeClass, &nativeMethod, 1);
Run Code Online (Sandbox Code Playgroud)
有问题的部分是jclass
在默认类加载器中无法访问类时获取值.如果类Native
驻留在运行在JVM内部的OSGi容器(例如Equinox)内的OSGi包中,则不是这种情况.
为了进入类,我使用Java函数返回Class<?>
我的类的实例:
public class Helper {
public static Class<?> getNativeClass() {
// Find bundle from system bundle context.
Bundle bundle = ... // details left out.
return bundle.loadClass("org.example.Native");
}
}
Run Code Online (Sandbox Code Playgroud)
此函数驻留在OSGi容器外部的类中.使用JNI从C++端调用此函数为我们提供了jobject
一个实例java.lang.Class<>
.
// Load the `Helper` class.
jclass helperClass = env->FindClass("org.example.Helper");
// Get the method `Helper.getNativeClass()`.
jmethodId mid = env->GetStaticMethodID(helperClass,
"getNativeClass",
"()Ljava/lang/Class;");
// Call `Helper.getNativeClass()`.
jobject nativeClassInstance = env->CallStaticObjectMethod(helperClass, mid);
Run Code Online (Sandbox Code Playgroud)
问题是我们确实需要'jclass'值(不是jobject
值).为了得到它,我实例化了我的Native
类的一个对象并从中得到了jclass
它.
// This is the jclass for 'java.lang.Class<>'.
jclass classClass = env->GetObjectClass(nativeClassInstance);
// Now get the method id for function 'newInstance()'
jmethodId newInstanceMid = env->GetMethodID(helperClass,
"newInstance",
"()Ljava/lang/Object;");
// Instantiate our 'Native' class calling 'Class<Native>.newInstance()'.
jobject nativeInstance = env->CallObjectMethod(classClass,
nativeClassInstance,
newInstanceMid);
// Now, I can get the desired 'jclass' of my 'Native' class.
jclass nativeClass = env->GetObjectClass(nativeInstance);
Run Code Online (Sandbox Code Playgroud)
但这只能起作用,因为我可以实例化我的Native
课程.
任何想法如何获得所需jclass
而不必实例化Native
类的对象?
您应该能够使用helper方法返回jobject
的类型Class<Native>
作为jclass
简单的方法:
jclass nativeClass = (jclass)nativeClassInstance;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2613 次 |
最近记录: |