在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
選項。