Copying C array to Java array using JNI

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

+4
source share
2 answers

There is also a function for the primitive "long" type to set individual elements in the JNI. So I believe you want to have 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 stored in the jclass JNI javaClass .

+5
source

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

I think your big problem is that you are trying to use unsigned integers in Java longs. Java longs are signed 64-bit numbers. After the conversion is correct, you can create an array of type jlong ​​in c, and then use the SetLongArrayRegion () method to return the numbers in java.

+2
source

Source: https://habr.com/ru/post/1302710/


All Articles