JNI: C++ float array to Java

Working on a project mixing C++ and Java, I was in need to pass a raw C++ float array back to Java. JNI is not the best documented piece of software (personal opinion) so it took me a while to figure it out.

This blog post will show how to do this in hopes of saving the next guy some time.

The C++ struct holding the raw 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 passing 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);

			// Reinterpret the field object as a jfloatArray
            jfloatArray* fa = reinterpret_cast<jfloatArray*>(&field_data);

			// Get raw access to the float array
            float* fa_raw = env->GetFloatArrayElements(*fa, nullptr);

			// Copy elements (you might want to use std::memcpy() instead)
            for (int i = 0; i < 16; i++)
                fa_raw[i] = fc.a[i];

			// Release the jfloatArray
			env->ReleaseFloatArrayElements(fa, fa_raw, 0);
        }
    }
    
    return foo_object;
}

And that’s it.

This blog post was inspired after asking for help on stackoverflow: https://stackoverflow.com/questions/65076094/passing-float-from-c-to-java-using-jni

comments powered by Disqus