Search code examples
c++java-native-interface

JNI: How to convert a group of data from c++ to Java


I'm 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 data on Java, I'm trying 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 correct this steps to return a structure/object with data? How is possible to fix the errors?


Solution

  • Converting everything to JNI types is not a good idea. Generally, it is better to create a peer object, i.e. a handle pointer to the native resource - like the hWnd in the Windows GUI Programming.