3

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 ?
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Viktor Apoyan
  • 10,655
  • 22
  • 85
  • 147

2 Answers2

1

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.)

Edward Thomson
  • 74,857
  • 14
  • 158
  • 187
0

You can do this, but you have to map the values yourself. You should take a look at this question: How to pass C structs back and forth to Java code in JNI?.

Community
  • 1
  • 1
Malcolm
  • 41,014
  • 11
  • 68
  • 91