0

I have an array of type Foo in my java code which I want to pass to c++. In the c++ code, I also have the same class named Foo. all I want is to transfer this array via 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

I understand this error but what should I do to eliminate it? should I cast the jobject to type Foo? will c++ understand the object that way? or am I missing some JNI calls?

1 Answer 1

3

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. Having the same name does not produce this effect across the JNI boundary, regardless of the similarity or dissimilarity of the types' members. 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? will c++ understand the object that way? or am I missing some JNI calls?

That depends to some extent on the nature of the C++ Foo, and of how you want it to work.

One option would be to initialize each C++ Foo by copying the needed members of the corresponding Java Foo. That would involve JNI calls to read object fields or to invoke methods on the jobject, or both. Details depend on the two Foos.

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. That's pretty much the same thing as the other, really, but with finer granularity and, accordingly, different performance tradeoffs.

Sign up to request clarification or add additional context in comments.

2 Comments

I am new to JNI so a simple example would help a lot, thanks.
@user7331538, the question is too general for me to have any confidence about what points an example should focus upon. If you're so new to JNI that you're uncertain how to formulate a more specific followup, then I suggest choosing and going through a JNI tutorial. You'll need that anyway, no matter what sort of example I might provide.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.