Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a String array on a JNI method

I need to get a List of Strings (char*) from C++ and return it to Java.

How can I do that?

I think one solution is return a big string pre-defined like: "[item1][item2]" and make a split on Java, but it doesn't look like the right approach.

like image 660
Marcos Vasconcelos Avatar asked May 18 '11 15:05

Marcos Vasconcelos


2 Answers

Look at NewObjectArray into the JNI doc.

Basically you can return from the JNI function an Array Of String (Java) an then transform it in a List or a whatever kind of Collection type.

Peudo code:

Java:

....
public List<String> getFooAsList(){
  return new ArrayList(this.getData());
}  
private native String[] getData();

JNI

#include <jni.h>


  JNIEXPORT jobjectArray JNICALL 
               como_foo_bar_getData
  (JNIEnv *env, jobject jobj){

    jobjectArray ret;
    int i;

    char *data[5]= {"A", "B", "C", "D", "E"};

    ret= (jobjectArray)env->NewObjectArray(5,env->FindClass("java/lang/String"),env->NewStringUTF(""));

    for(i=0;i<5;i++) env->SetObjectArrayElement(ret,i,env->NewStringUTF(data[i]));

    return(ret);
 }

Not tested!!!

Let me know if it works for u

Regards

like image 177
Francesco Laurita Avatar answered Oct 22 '22 09:10

Francesco Laurita


ret= (jobjectArray)env->NewObjectArray(5,env->FindClass("java/lang/String"),env->NewStringUTF(""));

I think the initial element initialized to "" (empty string)

env->NewStringUTF("")

is not needed, as you assign a new value to the array element just after:

for(i=0;i<5;i++) env->SetObjectArrayElement(ret,i,env->NewStringUTF(data[i]));

A simple "NULL" would be enough in this case, as the initial element specified will be electable for garbage collection as soon as the next line is executed. It's like writing the following in Java code:

int i = 0;
i = 1;

Or worse:

Object object = new BigObjectVeryHeavyToInitialize();
object = new AnotherObject();

Your favorite IDE would issue you a little warning for that.

like image 34
Laurent_Psy Avatar answered Oct 22 '22 08:10

Laurent_Psy