将2d数组从C++传递到Java并返回到C++

Jus*_*ted 4 c++ java arrays java-native-interface multidimensional-array

如何将二维数组从C++传递给Java并使用JNI返回到C++?

Sample2.java

public static int[][] intArrayMethod(int[][] n){
    for (int i = 0; i < 10; i++){
        for (int j = 0; j < 10; j++){
            n[i][j] = 2;
        }
    }
    return n;
}
Run Code Online (Sandbox Code Playgroud)

CppSample.cpp

int main(){
    JavaVMOption options[1];
    JNIEnv *env;
    JavaVM *jvm;
    JavaVMInitArgs vm_args;
    long status;
    jclass cls;
    jmethodID mid;

    options[0].optionString = "-Djava.class.path=.";
    memset(&vm_args, 0, sizeof(vm_args));
    vm_args.version = JNI_VERSION_1_2;
    vm_args.nOptions = 1;
    vm_args.options = options;
    status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);

    jint cells[10][10]; // my 2d array
    for (int i = 0; i < 10; i++){
        for (int j = 0; j < 10; j++){
            cells[i][j] = 1;
        }
    }

    if (status != JNI_ERR){
        cls = env->FindClass("Sample2");
        if (cls != 0){
            mid = env->GetStaticMethodID(cls, "intArrayMethod", "(I)I");
            if (mid != 0){
                cells = env->CallStaticIntMethod(cls, mid, cells);
                for (int i = 0; i < 10; i++){
                    for (int j = 0; j < 10; j++){
                        printf("%d", cells[i][j]);
                    }
                }
            }
        }
        jvm->DestroyJavaVM();
        return 0;
    }
    else{
        return 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

我不确定在c ++和java之间传递二维数组的正确方法是什么.

希望你能指导我,谢谢!

Win*_*ute 8

这并不像单调乏味那么困难.一般的问题是Java中的数组与C++中的数组完全不同,并且(有点)与不可调整大小的向量更相似.不可能直接将C++数组传递给Java 1因为Java不知道如何处理它.所以我们需要转换功能,例如:

将2D数组从C++转换为Java

// The template bit here is just to pick the array dimensions from the array
// itself; you could also pass in a pointer and the dimensions. 
template<std::size_t OuterDim, std::size_t InnerDim>
jobjectArray to_java(JNIEnv *env, int (&arr)[OuterDim][InnerDim]) {
  // We allocate the int array first
  jintArray    inner = env->NewIntArray   (InnerDim);
  // to have an easy way to get its class when building the outer array
  jobjectArray outer = env->NewObjectArray(OuterDim, env->GetObjectClass(inner), 0);

  // Buffer to bring the integers in a format that JNI understands (jint
  // instead of int). This step is unnecessary if jint is just a typedef for
  // int, but on OP's platform this appears to not be the case.
  std::vector<jint> buffer;

  for(std::size_t i = 0; i < OuterDim; ++i) {
    // Put the data into the buffer, converting them to jint in the process
    buffer.assign(arr[i], arr[i] + InnerDim);

    // then fill that array with data from the input
    env->SetIntArrayRegion(inner, 0, InnerDim, &buffer[0]);
    // and put it into the outer array
    env->SetObjectArrayElement(outer, i, inner);

    if(i + 1 != OuterDim) {
      // if required, allocate a new inner array for the next iteration.
      inner = env->NewIntArray(InnerDim);
    }
  }

  return outer;
}
Run Code Online (Sandbox Code Playgroud)

从Java到C++

// Note that this function does not return an array but a vector of vectors
// because 2-dimensional Java arrays need not be rectangular and have
// dynamic size. It is not generally practical to map them to C++ arrays.
std::vector<std::vector<int> > from_java(JNIEnv *env, jobjectArray arr) {
  // always on the lookout for null pointers. Everything we get from Java
  // can be null.
  jsize OuterDim = arr ? env->GetArrayLength(arr) : 0;
  std::vector<std::vector<int> > result(OuterDim);

  for(jsize i = 0; i < OuterDim; ++i) {
    jintArray inner = static_cast<jintArray>(env->GetObjectArrayElement(arr, 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);
      result[i].resize(InnerDim);

      jint *data = env->GetIntArrayElements(inner, 0);
      std::copy(data, data + InnerDim, result[i].begin());
      env->ReleaseIntArrayElements(inner, data, 0);
    }
  }

  return result;
}
Run Code Online (Sandbox Code Playgroud)

如你所见,它们非常简单; 一个人真的只需知道JNI要调用什么函数(或者实际上,在哪里可以找到文档).

调用Java函数

至于调用Java函数,你几乎是正确的.有两件事需要改变:

mid = env->GetStaticMethodID(cls, "intArrayMethod", "(I)I");
Run Code Online (Sandbox Code Playgroud)

如果intArrayMethod是的话会工作的int intArrayMethod(int).事实上,你需要

mid = env->GetStaticMethodID(cls, "intArrayMethod", "([[I)[[I");
Run Code Online (Sandbox Code Playgroud)

在这些签名字符串中,I代表int,[Ifor int[][[Ifor int[][].一般来说,[type代表type[].

和这里:

cells = env->CallStaticIntMethod(cls, mid, cells);
Run Code Online (Sandbox Code Playgroud)

两件事情:

  1. 正如一开始所提到的那样,cells不能按原样传递,因为Java不理解它是什么; 它需要首先转换为Java数组(例如,上面的转换函数),和
  2. intArrayMethod不是IntMethod; 它不会返回int复杂的数据类型.正确的调用必须使用CallStaticObjectMethod并转换jobject它返回实际有用的JNI类型.

一个正确的方法是:

jobjectArray java_cells = static_cast<jobjectArray>(env->CallStaticObjectMethod(cls, mid, to_java(env, cells)));
Run Code Online (Sandbox Code Playgroud)

这为您提供了一个jobjectArray可以转换为带有其他转换函数的向量的C++向量的方法:

std::vector<std::vector<int> > cpp_cells = from_java(env, java_cells);
Run Code Online (Sandbox Code Playgroud)

然后可以像任何矢量一样使用它.

我可以提到一些样式问题(例如依赖于Java代码中的数组总是10x10,或者使用或C函数哪里有更好的(读取:类型安全)C++替代品 - 我在看着你,printf),但它们似乎没有引发这个特定程序的问题.

1除了指针将其传递回本机代码