Passing float[] from C++ to Java using JNI

Viewed 370

I am attempting to "pass" (i.e. copy) a raw float array from C++ to Java. The C++ structure holding the source array:

struct foo_cpp {
    float a[16];
};

The Java class holding the destination array:

public class foo_java {
    public float a[];

    public foo_java() {
        a = new float[16];
    }
}

The C++ function trying to pass the data to the Java class:

extern "C" JNIEXPORT jobject JNICALL Java_com_example_myapp_Controller_process_1frame(JNIEnv *env, jclass clazz)
{
    // C++ "source array"
    foo_cpp fc;
    // Initialize fc.a here...

    // Convert from cpp to java
    jobject foo_object;
    {
        // Create the foo object
        jclass foo_class_id = env->FindClass("com/example/myapp/foo_java");
        jmethodID foo_ctor_id = env->GetMethodID(foo_class_id, "<init>", "()V");
        foo_object = env->NewObject(foo_class_id, foo_ctor_id);

        // Get the field ID
        jfieldID field_id = env->GetFieldID(foo_class_id, "a", "[F");

        // Set the fields
        {
            // Get pointer to Java object float array (Get pointer to Java class foo_java::a)
            jobject field_data = env->GetObjectField(foo_object, field_id);
            jfloatArray *fa = reinterpret_cast<jfloatArray*>(&field_data);
            float *fa_raw = env->GetFloatArrayElements(*fa, nullptr);
            for (int i = 0; i < 16; i++)
                fa_raw[i] = static_cast<float>(fc.a[i]);
        }
    }
    
    return foo_object;
}

However, when running this, the values in the java object are not as expected.

What am I missing / doing wrong?

1 Answers

The code mentioned in the question turned out to work as expected. The float values where correct and it was a classic case of misinterpretation / layered problems.

However, as @Michael pointed out in the comment: A call to ReleaseFloatArrayElements() is necessary to prevent leaking memory.

I've created a blog post regarding this: https://blog.insane.engineer/post/cpp_length_prefixed_strings/

Related