简体   繁体   中英

How to call a java function which returns the object of a class in a c++ program and receive that object?

I am trying to call a java function in a c++ program which returns a object of a class given below:

class Test1   
{  
    int a;
    int b;
}

Here is my c++ code:

#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();
}

Now how do i convert it into the object of the class Test1? Or do I have to use some other method?

EDITED

How can i pass the object of a class as a argument and get that object on java part?

The class is same :

class Test1   
{  
    int a;
    int b;
}

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

SOLUTION:

Here is how i get fields :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM