简体   繁体   English

JNI如何将Java对象数组传递给相同对象类型的C ++数组

[英]JNI how to pass an array of java objects to a c++ array of the same object type

I have an array of type Foo in my java code which I want to pass to c++. 我要传递给c ++的java代码中有一个Foo类型的数组。 In the c++ code, I also have the same class named Foo . 在c ++代码中,我还有一个名为Foo的相同类。 all I want is to transfer this array via JNI. 我想要的只是通过JNI传输此数组。

I have a call like this: 我有这样的电话:

#include "headers/Foo.h"

extern "C"
    JNIEXPORT void
    JNICALL Java_main_Main_Interface(JNIEnv *env, jobject obj, jobjectArray foo){
        jint size = env->GetArrayLength(foo);
        Foo cfoo[size];
        for(int i = 0; i < size; i++){
            cfoo[i] = env->GetObjectArrayElement(foo, i);
        }
}

This is, however, giving me an error: Type 'Foo' and 'jobject' are not compatible 但是,这给我一个错误: Type 'Foo' and 'jobject' are not compatible

I understand this error but what should I do to eliminate it? 我知道此错误,但是应该怎么消除呢? should I cast the jobject to type Foo? 我应该将jobject转换为Foo类型吗? will c++ understand the object that way? C ++将以这种方式理解对象吗? or am I missing some JNI calls? 还是我错过了一些JNI电话?

I understand this error 我了解这个错误

No, I don't think you do. 不,我不认为你这样做。

The type named Foo in your C++ code is not related to your Java Foo . C ++代码中名为Foo的类型与Java Foo不相关。 Having the same name does not produce this effect across the JNI boundary, regardless of the similarity or dissimilarity of the types' members. 无论类型成员的相似性或不相似性,具有相同的名称不会在JNI边界上产生这种影响。 Thus, yours is not merely a syntactic issue, but rather a much more fundamental one. 因此,您的问题不仅是句法问题,而且是更为根本的问题。

but what should I do to eliminate it? 但是我应该怎么做才能消除呢? should I cast the jobject to type Foo? 我应该将jobject转换为Foo类型吗? will c++ understand the object that way? C ++将以这种方式理解对象吗? or am I missing some JNI calls? 还是我错过了一些JNI电话?

That depends to some extent on the nature of the C++ Foo , and of how you want it to work. 这在某种程度上取决于C ++ Foo的性质以及您希望它如何工作。

One option would be to initialize each C++ Foo by copying the needed members of the corresponding Java Foo . 一个选择是将初始化每个C ++ Foo通过复制对应的Java的所需成员Foo That would involve JNI calls to read object fields or to invoke methods on the jobject , or both. 这将涉及JNI调用,以读取对象字段或调用jobject上的方法,或同时执行这两者。 Details depend on the two Foo s. 详细信息取决于两个Foo

Alternatively, you could rewrite or subclass the C++ Foo to be a wrapper for a jobject representing the corresponding Java Foo , with C++ methods delegating to the jobject via JNI calls. 或者,您可以重写或子类化C ++ Foo ,使其成为表示对应的Java Foojobject的包装,而C ++方法通过JNI调用委派给jobject That's pretty much the same thing as the other, really, but with finer granularity and, accordingly, different performance tradeoffs. 确实,这几乎与另一件事相同,但是具有更精细的粒度,因此会有不同的性能折衷。

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

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