在C++中调用Java方法并处理返回值,可以使用Java Native Interface (JNI)
MyClass.java
:public class MyClass {
public int add(int a, int b) {
return a + b;
}
}
javac
编译Java类,并使用javah
生成JNI头文件:javac MyClass.java
javah -jni MyClass
main.cpp
,并实现JNI函数:#include <jni.h>
#include <iostream>
#include "MyClass.h"
JNIEXPORT jint JNICALL Java_MyClass_add(JNIEnv *env, jobject obj, jint a, jint b) {
jclass cls = env->GetObjectClass(obj);
jmethodID mid = env->GetMethodID(cls, "add", "(II)I");
jint result = env->CallIntMethod(obj, mid, a, b);
return result;
}
int main() {
JavaVMOption options;
JNIEnv *env;
JavaVM *jvm;
options.optionString = "-Djava.class.path=./";
JNI_CreateJavaVM(&jvm, (void**)&env, &options);
jclass cls = env->FindClass("MyClass");
jmethodID mid = env->GetMethodID(cls, "add", "(II)I");
jobject obj = env->NewObject(cls, nullptr, 5, 3);
jint result = env->CallIntMethod(obj, mid, 5, 3);
std::cout << "Result: " << result << std::endl;
env->DeleteLocalRef(obj);
env->DeleteLocalRef(cls);
jvm->DestroyJavaVM();
return 0;
}
g++ -I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux main.cpp -o main -L${JAVA_HOME}/jre/lib/amd64/server -ljvm
./main
输出结果应为:
Result: 8
这个示例展示了如何在C++中调用Java方法并处理返回值。注意,这里的示例是针对Linux系统的,如果你使用的是Windows系统,需要相应地修改-I
和-L
选项。