Convert C ++ primitive type vector to java primitive array

I use a third-party C ++ API for my project and have functions with return values ​​with types std::vector<int> , std::vector<bool> , std::vector<double> . I need to pass variables with these types in Java. Therefore, I use JNI, and my function has return values ​​with types jintArray , jbooleanArray , jdoubleArray .

I use the following code to convert to double :

 std::vector<double> data; //fill data jdouble *outArray = &data[0]; jdoubleArray outJNIArray = (*env).NewDoubleArray(data.size()); // allocate if (NULL == outJNIArray) return NULL; (*env).SetDoubleArrayRegion(outJNIArray, 0 , data.size(), outArray); // copy return outJNIArray; 

I have no problem with this block of code. But when I want to do this for int and bool types, the problem arises as follows:

 std::vector<int> data; //fill data jint *outArray = &data[0]; 

and

 std::vector<bool> data; //fill data jboolean *outArray = &data[0]; 

The problem is with jint and jboolean , as:

 typedef long jint; typedef unsigned char jboolean; 

and for jdouble :

 typedef double jdouble; 

As you can see, my convenient solution for double does not work for int and bool types, since their typedefs do not match.

So my question is: how can I do this conversion for all primitive types conveniently ?

Thank you in advance

+6
source share
1 answer

Since data types can have different sizes, you need to copy the vector. The easiest way to do this is

 std::vector<jboolean> tmp(data.begin(), data.end()); jboolean *outArray = &tmp[0]; 

Of course, you can highlight jBooleanArray and set elements in a for loop or write a wrapper for it that behaves like an STL container.

+2
source

Source: https://habr.com/ru/post/970373/


All Articles