aaddesso
aaddesso

Reputation: 41

JNI: set jobjectArray from c++

I'm using the JNI for the first time. I have this problem: in my java code there is an object that has an array of another object (defined by me) as field. Now, I need to set this object-array field from the native code. How can I do?

Thank you in advance! :)

Angela


My java code:

public class MyClass {

    private MyObject[] array; 
 ....
}

I need to set array from c++.

Upvotes: 0

Views: 1120

Answers (1)

Botje
Botje

Reputation: 30817

I assume you are passed a JNIEnv *env and a MyClass object from Java as object and that your classes are not in a package.

First we need to look up some classes and the constructor for MyObject objects:

jclass cls_MyClass = env->FindClass("MyClass");
jfieldID fld_MyClass_array = env->GetFieldID(cls_MyClass, "array", "[LMyObject;");

jclass cls_MyObject = env->FindClass("MyObject");
jmethodID ctr_MyObject = env->GetMethodID(cls_MyObject, "<init>", "(I)V");

Now we construct an array of size 10 and fill it with instances:

jobjectArray arr = env->NewObjectArray(10, cls_MyObject, nullptr);
for (int i = 0; i < 10; i++) {
  jobject elem = env->NewObject(cls_MyObject, ctr_MyObject, i);
  env->SetObjectArrayElement(arr, i, elem);
  env->DeleteLocalRef(elem); // Keep amount of local references constant
}

And we finally assign it to the array field:

env->SetObjectField(obj, fld_MyClass_array, arr);

Upvotes: 1

Related Questions