user402642
user402642

Reputation:

Java JNI - Is it possible to set an individual primitive array element in Java from C++

Basically, I've been doing the following to retrieve Java Instance Fields (in this case, an int) and setting it to a new value like the following:

jclass cls = env->GetObjectClass(obj);
jfieldID fid = env->GetFieldID(cls, "myVariable", "I");
env->SetIntField(obj, fid, (jint)2012);

However, I'd like to do this for an individual int element in a java int array such that:

jclass cls = env->GetObjectClass(obj);
jfieldID fid = env->GetFieldID(cls, "myVariableArray", "[I");
PSUDOCODE: <"SET myVariableArray[0] = 2013" ... Is there a method for this?>

Is there such a thing?

Upvotes: 10

Views: 8756

Answers (2)

Sdra
Sdra

Reputation: 2347

If you just want to change only one or few values I highly suggest to use SetIntArrayRegion as it avoids copying back and forth the whole array.

jintArray jMyArray = (jintArray)env->GetObjectField( obj, fid );
// jMyArray[0] = 2013
jint elements[] = { 2013 };
env->SetIntArrayRegion( jMyArray, 0, 1, elements );

for more JNI best practices refer to this article from IBM ;)

Upvotes: 5

user402642
user402642

Reputation:

I found the answer after looking through 15+ documents.

// Grab Fields
jclass cls = env->GetObjectClass(obj);
jfieldID fid = env->GetFieldID(cls, "testField", "[I");

jintArray jary;
jary = (jintArray)env->GetObjectField(obj, fid);
jint *body = env->GetIntArrayElements(jary, 0);
body[0] = 3000;
env->ReleaseIntArrayElements(jary, body, 0);

ReleaseIntArrayElements is key ... it returns a copy back to the java Instance Variable.

Upvotes: 10

Related Questions