Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying C Array into Java Array Using JNI

I have an array of unsigned integers in C and a java array of longs. I want to copy the contents of the unsigned integers to the java array. So far, the only function that I've found to do this is SetLongArrayRegion(), but this takes an entire buffer array. Is there a function to set only the individual elements of the java array?

like image 234
LandonSchropp Avatar asked Feb 28 '23 11:02

LandonSchropp


2 Answers

There is also a function for the primitive 'long' type to set individual elements in JNI. So I believe what you want to have is something like this

unsigned int* cIntegers = getFromSomewhere();
int elements = sizeof(cIntegers) / sizeof(int);

jfieldID jLongArrayId = env->GetFieldID(javaClass, "longArray", "[J");
jlongArray jLongArray = (jlongArray) env->GetObjectField(javaObject, jLongArrayId);
for (unsigned int i = 0; i < elements; ++i) {
   unsigned int cInteger = cIntegers[i];
   long cLong = doSomehowConvert(cInteger);
   env->SetLongArrayElement(jLongArray, i, (jlong) cLong);
}

if the long array in java is called longArray and the java class is saved in a JNI jclass variable javaClass.

like image 176
David Sauter Avatar answered Mar 02 '23 01:03

David Sauter


There is a SetObjectArrayElement() function, that works on non-native types. If you really, really wanted to use this approach, I think you could create an array of Longs. You may still have problems with type conversion though.

I think your big problem here is that you are trying to cast unsigned integers to Java longs. Java longs are signed 64 bit numbers. Once you have your conversion right, you can create an array of type jlong in c, and then use to SetLongArrayRegion() method to get the numbers back to java.

like image 31
TwentyMiles Avatar answered Mar 02 '23 00:03

TwentyMiles