Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Struct object in Java from C++

I have C++ struct:

typedef struct FunctionArgs
{
    char* url;
    char* info;
    int   id;
    bool  isWorking;
}

And C++ function, which as an argument get FunctionArgs struct, now I want to call from this function Java method and as argument to that method give FunctionArgs struct.

void func( const FunctionArgs& args )
{
    // Do some code ...

    env->CallObjectMethod( clazzObject, clazzMethod, args );

}

As you can see in env->CallObjectMethod( clazzObject, clazzMethod, *args ); function as third argument I give args which is FunctionArgs struct object.

In JAVA I have class and function:

class JFunctionArgs 
{
    String url;
    String info;
    int   id;
    boolean  isWorking;
}

public class SomeClass
{
    public void func( JFunctionArgs args )
    {

    }
}

I want to know

  1. Can I do something that I do env->CallObjectMethod( clazzObject, clazzMethod, args );, I mean can I give struct object to CallObjectMethod as an argument ?
  2. How can I get struct object in Java code func ?
like image 1000
Viktor Apoyan Avatar asked Apr 09 '26 05:04

Viktor Apoyan


1 Answers

You cannot. Assuming you actually need to consume this data in both Java and C, you will need to marshal between the Java Object and the C struct.

In your JNI code, you will need to create a new Java object and populate its data. For example:

jclass clazz = env->FindClass("JFunctionArgs");
jmethodID ctor = env->GetMethodID(clazz, "<init>", "()V");
jobject obj = env->NewObject(clazz, ctor);

jfieldID urlField = env->GetFieldID(clazz, "url", "Ljava/lang/String;");
env->SetObjectField(obj, urlField, env->NewString(functionArgs.url));

...etc.

(If, however, you only need to modify the struct's data in C, you can simply return a pointer to it and treat it as an opaque long in Java.)

like image 54
Edward Thomson Avatar answered Apr 11 '26 19:04

Edward Thomson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!