简体   繁体   English

JNI从Java到C ++的转换

[英]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? 我的c ++函数参数的类型为std::vector<float>&所以从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. 如果我是Java新手,如果我问错了问题,我深表歉意。

Actually i am passing image data which has array of float values from Java side. 实际上,我正在从Java端传递具有float值数组的图像数据。

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>&'

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. 它们通常是使用javah实用程序在已编译的Java类上生成的。 That way the JVM will be able to find it by namespace, class and method name in the loaded shared libraries (dynamic-link libraries). 这样,JVM将能够通过已加载的共享库(动态链接库)中的名称空间,类和方法名称找到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM