1

I have the following JNI method,

JNIEXPORT jobject JNICALL Java_projlib_DeserializeBuffer
(JNIEnv *env, jobject obj, jbyteArray inBufferData)

I have created a list of unsigned char* and filling it using some data extracted from the inBufferData in my C++ code

list<unsigned char*> returnBuffer

I want to return the returnBuffer to my Java code, where it will be a List of byte array, List<byte[]>.

Please tell me how to pass the list of unsigned char* via a jobject through JNI and then get it in Java for further processing.

1 Answer 1

1

You will not be able to do that directly. You will have to instantiate an instance of the needed Java list implementation (since List is an interface) in C++, put it in a jobject and then add jbytearray items to it from your list and then return the list.

EXAMPLE

Since I do not have a working JNI environment, this snippet is only illustrational (feel free to edit it when you get it working), but what you need could be achieved by this:

jclass arrayListClass = env->FindClass("java/util/ArrayList"); // Find ArrayList class
jmethodID constructor = env->GetMethodID(arrayListClass, "<init>", "()V"); // Find ArrayList constructor
jobject arrayList = env->NewObject(arrayListClass, constructor); // Create new ArrayList instance
jmethodID add = env->GetMethodID(arrayListClass, "add", "(Ljava/lang/Object;)Z"); // Find the ArrayList::add method
jbyteArray item =env->NewByteArray(10); // Instantiate a new byte[]
env->CallBooleanMethod(arrayList, add, item); // Add the byte[] to the ArrayList
Sign up to request clarification or add additional context in comments.

5 Comments

I am very new to C++, can you share some snippets?
@AnkitG I added a snippet but since I do not have a working JNI environment to test it on it is only illustrational, feel free to provide feedback or edit it.
@AnkitG I updated the snippet, the signature for the add method was wrong and it caused Java exception.
Thanks! Had one clarification. the data I want to return is not a ByteArray, it is a list<unsigned char*> returnBuffer in C++ and in the Java world it will be a ByteArray. From your code snippet, I will simply remove the line, jbyteArray item =env->NewByteArray(10); and in place of item, put my list/vector object. Let me know if that is a correct approach
@AnkitG In your question you mentioned List<byte[]> which seems correct. list<unsigned char*> is a list of pointers to arrays - so unless you have chosen the wrong container it is not the same as byte[]. How many items are in your list? If multiple then how do you hope to represent multiple arrays with one byte[]?

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.