How to access arrays within an object with JNI? - java-native-interface

JNI tutorials, for instance this one, cover quite well how to access primitive fields within an object, as well as how to access arrays that are provided as explicit function arguments (i.e. as subclasses of jarray). But how to access Java (primitive) arrays that are fields within an jobject? For instance, I'd like to operate on the byte array of the following Java object:
class JavaClass {
...
int i;
byte[] a;
}
The main program could be something like this:
class Test {
public static void main(String[] args) {
JavaClass jc = new JavaClass();
jc.a = new byte[100];
...
process(jc);
}
public static native void process(JavaClass jc);
}
The corresponding C++ side would then be:
JNIEXPORT void JNICALL Java_Test_process(JNIEnv * env, jclass c, jobject jc) {
jclass jcClass = env->GetObjectClass(jc);
jfieldID iId = env->GetFieldID(jcClass, "i", "I");
// This way we can get and set the "i" field. Let's double it:
jint i = env->GetIntField(jc, iId);
env->SetIntField(jc, iId, i * 2);
// The jfieldID of the "a" field (byte array) can be got like this:
jfieldID aId = env->GetFieldID(jcClass, "a", "[B");
// But how do we operate on the array???
}
I was thinking to use GetByteArrayElements, but it wants an ArrayType as its argument. Obviously I'm missing something. Is there a way to to this?

I hope that will help you a little (check out the JNI Struct reference, too):
// Get the class
jclass mvclass = env->GetObjectClass( *cls );
// Get method ID for method getSomeDoubleArray that returns a double array
jmethodID mid = env->GetMethodID( mvclass, "getSomeDoubleArray", "()[D");
// Call the method, returns JObject (because Array is instance of Object)
jobject mvdata = env->CallObjectMethod( *base, mid);
// Cast it to a jdoublearray
jdoubleArray * arr = reinterpret_cast<jdoubleArray*>(&mvdata)
// Get the elements (you probably have to fetch the length of the array as well
double * data = env->GetDoubleArrayElements(*arr, NULL);
// Don't forget to release it
env->ReleaseDoubleArrayElements(*arr, data, 0);
Ok here I operate with a method instead of a field (I considered calling a Java getter cleaner) but you probably can rewrite it for the fields as well. Don't forget to release and as in the comment you'll probably still need to get the length.
Edit: Rewrite of your example to get it for a field. Basically replace CallObjectMethod by GetObjectField.
JNIEXPORT void JNICALL Java_Test_process(JNIEnv * env, jclass c, jobject jc) {
jclass jcClass = env->GetObjectClass(jc);
jfieldID iId = env->GetFieldID(jcClass, "i", "I");
// This way we can get and set the "i" field. Let's double it:
jint i = env->GetIntField(jc, iId);
env->SetIntField(jc, iId, i * 2);
// The jfieldID of the "a" field (byte array) can be got like this:
jfieldID aId = env->GetFieldID(jcClass, "a", "[B");
// Get the object field, returns JObject (because Array is instance of Object)
jobject mvdata = env->GetObjectField (jc, aID);
// Cast it to a jdoublearray
jdoubleArray * arr = reinterpret_cast<jdoubleArray*>(&mvdata)
// Get the elements (you probably have to fetch the length of the array as well
double * data = env->GetDoubleArrayElements(*arr, NULL);
// Don't forget to release it
env->ReleaseDoubleArrayElements(*arr, data, 0);
}

In gcc 6.3 I get a warning saying "dereferencing type-punned pointer will break strict-aliasing rules" from a line like this:
jdoubleArray arr = *reinterpret_cast<jdoubleArray*>(&mvdata);
But since jdoubleArray is itself a pointer to class _jdoubleArray, there's no need to get the address before casting, and this static_cast works without warnings:
jdoubleArray arr = static_cast<jdoubleArray>(mvdata);

Related

ReleaseStringUTFChars with non-original jstring argument?

In order to minimize JNI marshalling, I want to store some strings on the C++ side as static variables via a setup method, use them in a different JNI method call rather than passing them each time, and then release the strings later with yet another JNI method call. For example,
C++ code:
static const char *stringValue1;
extern "C" JNIEXPORT void JNICALL
Java_mypackage_myclass_setValue1(JNIEnv* env, jclass jobj, jstring javaString) {
jboolean isCopy;
if(!env->IsSameObject(javaString, NULL)) {
const char *stringValue1= env->GetStringUTFChars(javaString, &isCopy);
}
}
extern "C" JNIEXPORT void JNICALL
Java_mypackage_myclass_execute(JNIEnv* env, jclass jobj, jint javaInt) {
// ... use the stringValue1 static variable - otherwise, this method would need another jstring argument.
}
extern "C" JNIEXPORT void JNICALL
Java_mypackage_myclass_releaseValue1(JNIEnv* env, jclass jobj, jstring javaString) {
if(stringValue1 != 0) {
env->ReleaseStringUTFChars(javaString, stringValue1);
}
}
Java code:
myclass.setValue1("hello")
for(int i = 0; i < 10; i++) {
myclass.execute(i); // execute needs the "hello" string, but we try to store it in the C++ side rather than pass it in each loop iteration.
}
myclass.releaseValue1("hello");
Is this a valid JNI pattern? In all of the JNI examples I have seen, both calls to GetStringUTFChars and ReleaseStringUTFChars occur in the same method/scope. In this example, they do not occur in the same scope, and the jstring argument could possibly not be the same Java String either.
Yes, the documentation states
This array is valid until it is released by ReleaseStringUTFChars().
This is corroborated by the implementation in Hotspot, which just allocates off-heap memory for a copy.

How to obtain the name of a Java class from its corresponding jclass?

I have a jclass and I need to find out the name of the corresponding Java class. There is a well-received answer on SO for a similar question, however, it requires an object that's an instance of this class: https://stackoverflow.com/a/12730789/634821
I don't always have an instance where having the name of a jclass would be very useful, and I find it hard to believe that Java has no way to find a class's name, which is obviously a static property, with only static methods. So, is it doable, and how?
A jclass is a jobject subclass that references a java Class object.
So, cut the first few lines off the answer you found:
jclass input = ...; // Class<T>
jclass cls_Class = env->GetObjectClass(input); // Class<Class>
// Find the getName() method on the class object
mid = env->GetMethodID(cls_Class, "getName", "()Ljava/lang/String;");
// Call the getName() to get a jstring object back
jstring strObj = (jstring)env->CallObjectMethod(input, mid);
// Now get the c string from the java jstring object
const char* str = env->GetStringUTFChars(strObj, NULL);
// Print the class name
printf("\nCalling class is: %s\n", str);
// Release the memory pinned char array
env->ReleaseStringUTFChars(strObj, str);

How can I return vector<vector<float>> from JNI?

I have a function in C++:
std::vector<std::vector<float>> const &GetVertices() { return m_Vertices; }
I need to return this value to Java through JNI.
So, because of the fact that I need to return vector of vector, I think that I have to use jobjectArray, like this:
extern "C" JNIEXPORT jobjectArray JNICALL
Java_com_google_ar_core_examples_
java_helloar_HelloArActivity_fillListWithData(
JNIEnv *env,
jobject /* this */
)
In Java, I have this method:
public native Object[] fillListWithData();
So, my question is, how to convert vector<vector<float>> to jobjectArray?
I know that there is a method that could create jobjectArray:
jobjectArray verticesArr = env->NewObjectArray(verticesVec.size(), WHAT CLASS SHOULD BE HERE?,NULL);
Then how can I put in the values ?
Full class implementation
extern "C" JNIEXPORT jobjectArray JNICALL
Java_com_google_ar_core_examples_java_
helloar_HelloArActivity_fillListWithData(
JNIEnv *env,
jobject /* this */
) {
//verticesVec
vector<vector<float>> verticesVec = initializer->GetVertices(); // THIS VECTOR I NEED TO CONVERT TO JOBJECTARRAY
jobjectArray verticesArr = env->NewObjectArray(verticesVec.size(), WHAT CLASS SHOULD BE HERE?,NULL);
//HOW TO FILL THE ARRAY HERE??
return verticesArr;
}
You have to play with java.util.Vector. This way, you can make a very simple mapping of
(C++ side) vector<vector<float> > ---> Vector<Vector<Float>> (Java side)
The code itself will be little bit ugly. Remember that playing with JNI is not quite pleasant experience (due to esoteric syntax).
Anyway, what you want to do is to create all the stuff on C++ side and pass it back to Java.
Just an excerpt
vector<vector<float> > vect {
{ 1.1, 1.2, 1.3 },
{ 2.1, 2.2, 2.3 },
{ 3.1, 3.2, 3.3 }
};
...
...
jclass vectorClass = env->FindClass("java/util/Vector");
...
jclass floatClass = env->FindClass("java/lang/Float");
...
jmethodID mid = env->GetMethodID(vectorClass, "<init>", "()V");
jmethodID addMethodID = env->GetMethodID(vectorClass, "add", "(Ljava/lang/Object;)Z");
// Outer vector
jobject outerVector = env->NewObject(vectorClass, mid);
...
for(vector<float> i : vect) {
// Inner vector
jobject innerVector = env->NewObject(vectorClass, mid);
for(float f : i) {
jmethodID floatConstructorID = env->GetMethodID(floatClass, "<init>", "(F)V");
...
// Now, we have object created by Float(f)
jobject floatValue = env->NewObject(floatClass, floatConstructorID, f);
...
env->CallBooleanMethod(innerVector, addMethodID, floatValue);
}
env->CallBooleanMethod(outerVector, addMethodID, innerVector);
}
env->DeleteLocalRef(vectorClass);
env->DeleteLocalRef(floatClass);
You can find full sample code here:
https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo045
Once you run the test, you can see that C++ based data was passed to Java
> make test
/Library/Java/JavaVirtualMachines/jdk-12.0.1.jdk/Contents/Home/bin/java -Djava.library.path=:./lib -cp target recipeNo045.VectorOfVectors
library: :./lib
[1.1,1.2,1.3]
[2.1,2.2,2.3]
[3.1,3.2,3.3]
Depends a bit on how you want to operate on the data in Java, e.g. add more elements? You didn't mention this so the answer can't be more specific. But perhaps you want "java/util/ArrayList" of float.
The following answer should point you in the right direction:
return a jobjectArray which contains lists of data.
The code would look similar for other types of lists. A bit of web search will provide several solutions.
In case speed (CPU/latency) and data volume are not important, instead of all the messy handling of Java datastructures I would generally recommend serializing your data to JSON and return as string. Using e.g. JsonCpp it's easy to serialize C++ data types including objects to JSON, and on the Java side there are several packages for deserialization (web search again) and many Java frameworks come with builtin tools for this.

JNI Calling Java Method With Array Parameter

I am trying to call a java method from cpp. I seem to have no problem using strings, int, etc. One problem I am having those is passing an int array parameter over. Can someone tell me what I did wrong? I apologize if it is a very small error and I just totally missed it.
JNIEXPORT void JNICALL
Java_basket_menu_MenusActivity_submitInfo(JNIEnv *, jclass){
int placement[2] = { 5, 4 };
jclass cls = env->FindClass("basket/menu/MenusActivity");
jmethodID mid2 = env->GetStaticMethodID(cls, "PlaceMe", "([I)V");
env->CallStaticVoidMethod(cls, mid2, placement);
}
You need to create a jintArray and copy the contents of placement to it:
jintArray arr = env->NewIntArray(2);
env->SetIntArrayRegion(arr, 0, 2, placement);
env->CallStaticVoidMethod(cls, mid2, arr);
Refer to the documentation for more information about these functions.

in JNI, how to assign values to jobjectArray?

I have an array of objects which is initialized in Java as shown below:
Record[] pRecords = new Record[5];
ret = GetRecord(pRecords);
I passed this array to the JNI, from JNI it will call CPP, and finally the array will get filled.
JNIEXPORT jint JNICALL Java_GetRecord
(JNIEnv *jEnv, jobject ObjApp, jobjectArray jRecords)
{
Record *pRecords = (Record *)malloc(5*sizeof(Record ));
ret = Get_Record(pRecords); // call to CPP
if(SUCCESS == ret)
{
jclass c = (jEnv)->GetObjectClass(jRecords);
jfieldID fid = (jEnv)->GetFieldID(c, "m_session", "I");
(jEnv)->SetIntField (jRecords, fid, pRecords [0].value);
}
}
I am getting fid NULL. How to assign pRecords[0].value to 0th array of jRecords ?
A jobjectArray is not a pointer to the first element of the array. Remember that Java arrays are themselves first-class objects.
fid is 0 because you're looking for a member m_session in the class that represents an array of the Java class Record; of course the array class has no such member. You need to do a FindClass() to get the Record class, and then look for the member in there.
Then you proceed to try to set that member. If it's actually a member of the Record class, I'd imagine you want to set the value of that member in each array element in a loop, yes? Certainly not in the array itself, as you're trying to do. For each array element you need to call the appropriate method to get the object in that array position, then operate on that object.