gpt4 book ai didi

java - 如何在c++程序中调用返回类对象的java函数并接收该对象?

转载 作者:行者123 更新时间:2023-12-02 01:31:24 28 4
gpt4 key购买 nike

我试图在 C++ 程序中调用 java 函数,该函数返回下面给出的类的对象:

class Test1   
{
int a;
int b;
}

这是我的 C++ 代码:

#include <iostream>
#include <jni.h>
#include <cstdlib>

int main()
{
JavaVM *jvm;
JNIEnv *env;


JavaVMInitArgs vm_args;
JavaVMOption* options = new JavaVMOption[1];
options[0].optionString = "-Djava.class.path=/home/user";
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.options = options;
vm_args.ignoreUnrecognized = false;

jint rc = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
delete options;
if (rc != JNI_OK)
{
std::cin.get();
exit(EXIT_FAILURE);
}

std::cout << "JVM load succeeded: Version ";
jint ver = env->GetVersion();
std::cout << ((ver>>16)&0x0f) << "."<<(ver&0x0f) << std::endl;


jclass cls2 = env->FindClass("Server11");
if(cls2 != nullptr)
{
std::cout << "Class Server11 found" << std::endl;

jmethodID mid = env->GetStaticMethodID(cls2, "myJavaFunction", "()LTest1;");
if(mid != nullptr)
{
jobject obj = env->CallStaticObjectMethod(cls2, mid);

// Now how to convert obj into Test1??
}
}

jvm->DestroyJavaVM();
}

现在如何将其转换为 Test1 类的对象?或者我必须使用其他方法吗?

已编辑

如何将类的对象作为参数传递并在 java 部分获取该对象?

类(class)相同:

class Test1   
{
int a;
int b;
}

jmethodID mid = env->GetStaticMethodID(cls2, "myJavaFunction", "(/*WHAT SHOULD WRITE HERE*/)LTest1;");

最佳答案

解决方案:

这是我获取字段的方法:

jobject obj = env->CallStaticObjectMethod(cls2, mid);
jclass jc = env->GetObjectClass(obj);
jfieldID jf = env->GetFieldID(jc, "a", "I");
jint a = env->GetIntField(obj, jf);

关于java - 如何在c++程序中调用返回类对象的java函数并接收该对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57554440/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com