我正在尝试如何从 C++ 调用方法,我已经做到了:
#include <jni.h>
#include <iostream>
// Function to create the JVM and call the sayHi method
void callJavaSayHi() {
// Options to initialize the JVM
JavaVMOption options[1];
options[0].optionString = const_cast<char *>("-Djava.class.path=.");
// JVM initialization arguments
JavaVMInitArgs vm_args;
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.options = options;
vm_args.ignoreUnrecognized = false;
// Pointer to the JVM (Java Virtual Machine)
JavaVM *jvm;
// Pointer to native interface
JNIEnv *env;
// Create the JVM
jint res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
if (res != JNI_OK) {
std::cerr << "Failed to create JVM: " << res << std::endl;
exit(EXIT_FAILURE);
} else {
std::cout << "JVM created successfully" << std::endl;
}
// Find the Java class
jclass helloWorldClass = env->FindClass("HelloWorld");
if (helloWorldClass == nullptr) {
std::cerr << "Failed to find HelloWorld class" << std::endl;
jvm->DestroyJavaVM();
exit(EXIT_FAILURE);
} else {
std::cout << "HelloWorld class found" << std::endl;
}
}
但不知何故,
env->FindClass("HelloWorld")
无法返回类的指针。我收到“无法找到 HelloWorld 类”。
java 类很简单:
public class HelloWorld {
// Java method to be called from C++
public void sayHi() {
System.out.println("Hello from Java!");
}
}
我的文件结构是这样的:
-HelloWorld.class
-HelloWorld.java
-InvokeJavaMethod.cpp
我在这里做错了什么?
谢谢
问题是我编译它的 Java 版本与我在链接器中包含的版本不同:
g++ -o InvokeJavaMethod InvokeJavaMethod.cpp -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -L"%JAVA_HOME%\lib" -ljvm
JAVA_HOME 是 jdk-17,javac 是 jdk-21。