首先,您可以通过使用获取类参考
FindClass
之后,您可以使用该类的函数获取函数 ID
GetStaticMethodID and GetMethodID
然后运行
CallStaticVoidMethod, CallStaticIntMethod, and CallStaticObjectMethod...
所有这些都需要一个 JVM(如果你已经从 javah.exe 派生了头文件和 c++,你已经有了这个,所以可以跳过 JVM 创建),
JNIEnv* create_vm(JavaVM ** jvm) {
JNIEnv *env;
JavaVMInitArgs vm_args;
JavaVMOption options;
//Path to the java source code
options.optionString = "-Djava.class.path=D:\\Java Src\\TestStruct";
vm_args.version = JNI_VERSION_1_6; //JDK version. This indicates version 1.6
vm_args.nOptions = 1;
vm_args.options = &options;
vm_args.ignoreUnrecognized = 0;
int ret = JNI_CreateJavaVM(jvm, (void**)&env, &vm_args);
if(ret < 0)
printf("\nUnable to Launch JVM\n");
return env;
}
示例(c++):
jclass clas;
clas=FindClass("projectHello/helloWorldClass");
jmethodID meth;
meth = env->GetStaticMethodID(clas, "sayHello", "(I)V");
env->CallStaticVoidMethod(clas, meth,val); //val is (I) ---> parameter. Return type V ---->void
如果您不确定类背后的内容,则应检查错误,例如
if (env->ExceptionCheck()) {return ERR_GET_STATIC_METHOD_FAILED;}