JNI: how to convert a data group from C ++ to Java

I am trying to send some data from C ++ to java using JNI.

In C ++, I have:

  Array [0]:
 string name = "myName"
 int iterations = 16
 float value = 15
 ... etc 

So, I want to use JNI to return all the data in Java, I try this, but don't work

 JNIEXPORT jobjectArray JNICALL Java_com_testing_data_MainActivity_getDATA (JNIEnv * env, jobject obj) {// 1ΒΊ Create a temp object jobject dataClass {jstring name;  jint iterations;  jfloat value;  }; jobject tempObject = env->NewObject(); // Get data in c++ format int temp object type std::vector<dataClass > data = getDataClass(); // First error, must be a c++ class, how could i get it? // How much memory i need? int dataSize = data.size(); // Reserve memory in java format jint tempValues[dataSize]; jobjectArray tempArray = env->NewObjectArray(dataSize,dataClass,0); // 2ΒΊ Error, it doesn 't create the class // Temporal store data in jarray for (int i = 0; i < dataSize ; i++) { tempArray[i].name = data[i].name; tempArray[i].iterations = data[i].iterations; tempArray[i].value = data[i].value; } return tempArray; // return temp array 

}

Are these steps correct for returning a structure / object with data? How can I fix the errors?

+4
source share
2 answers

Converting all types of JNIs is not a good idea. As a rule, it is better to create a peer-to-peer object, i.e. A handle pointer to a native resource - for example, hWnd in the Windows GUI software.

+3
source

You can use a string to store all data as sequence data. The field is separated by a separator (for example, ":"), for example:

 std::string sequenceData = "my name" + ":" + "16" + ":" + "15" + ...; 

Pass this sequence in java, then split it to get the desired value. Use String.split() or StringTokenizer .

0
source

All Articles