Milind Deore
Milind Deore

Reputation: 3063

JNI conversion from Java to C++

My c++ function argument is of type std::vector<float>& so what is the best way to pass the parameter from JAVA? As vector make the array dynamic but the value i am passing is static. Apologies if i asked wrong question as i am new to Java.

Actually i am passing image data which has array of float values from Java side.

I tried following :

JNIEXPORT void JNICALL foo(JNIEnv* env, Jclass clazz, JfloatArray input){
jfloat* img = env->GetFloatArrayElements(input,NULL)

...
}

but it gives following error:

error: could not convert 'img' from 'jfloat* {aka float*}' to 'std::vector<float>&'

Upvotes: 0

Views: 1208

Answers (1)

Tom Blodget
Tom Blodget

Reputation: 20772

You simply have to copy the data to a new vector—that's the way vector works; it offers the ability to change the length.

JNIEXPORT void JNICALL Java_Main_foo(JNIEnv *env, jclass clazz, jfloatArray input)
{
    float* array = env->GetFloatArrayElements(input, NULL);
    jsize len = env->GetArrayLength(input);
    std::vector<float> img (array, array+len );
    // assuming foo will not alter img
    env->ReleaseFloatArrayElements(input, array, JNI_ABORT);
    foo(img);
}

Note: Your native function signature looks a bit suspicious. They are typically generated using the javah utility on compiled Java classes. That way the JVM will be able to find it by namespace, class and method name in the loaded shared libraries (dynamic-link libraries).

Upvotes: 1

Related Questions