首页 > 解决方案 > 如何将 Java double[][] 转换为 C++> JNI?

问题描述

我有一个二维 Java 双数组:

 double[][] jdestination_list = new double[][];

我如何将其转换为:

vector<vector<double>>  destinationListCpp;

我的 JNI 调用如下:

extern "C"
JNIEXPORT void JNICALL
Java_JNI_Call(JNIEnv *env, jobject thiz, jobjectArray jdestination_list,)

    // always on the lookout for null pointers. Everything we get from Java
    // can be null.
    jsize OuterDim = jdestination_list ? env->GetArrayLength(jdestination_list) : 0;
    std::vector<std::vector<double> > destinationListCpp(OuterDim);

for(jsize i = 0; i < OuterDim; ++i) {
    jdoubleArray inner = static_cast<jdoubleArray>(env->GetObjectArrayElement(jdestination_list, i));

    // again: null pointer check
    if(inner) {
        // Get the inner array length here. It needn't be the same for all
        // inner arrays.
        jsize InnerDim = env->GetArrayLength(inner);
        destinationListCpp[i].resize(InnerDim);

        jdouble *data = env->GetDoubleArrayElements(inner, 0);
        std::copy(data, data + InnerDim, destinationListCpp[i].begin());
        env->ReleaseDoubleArrayElements(inner, data, 0);
    }
}

我不断得到:

对 void Clas::Java_JNI_Call 的未定义引用

关于如何做到这一点的任何建议?

标签: javac++java-native-interface

解决方案


此代码生成一个名为的C类型函数Java_JNI_Call

extern "C"
JNIEXPORT void JNICALL
Java_JNI_Call(JNIEnv *env, jobject thiz, jobjectArray jdestination_list,)

C类型函数(注意extern "C"...)不是任何类的成员,它不能被重载,并且函数名称不会像 C++ 函数那样经历名称修改。

此错误消息抱怨您没有提供C++函数的定义Clas::Java_JNI_Call

undefined reference to void Clas::Java_JNI_Call

因为你没有。

JNI 调用在技术上是C函数,而不是 C++ 函数。您可以通过 JNI 的registerNatives()函数在C 和 C++ 调用约定兼容的系统上使用 C++ 函数,但您必须使用顶级或静态类方法,因为 JNI 调用没有可用作 C++ 的关联 C++ 对象this.


推荐阅读