I'm using a third party C++ API for my project and it has functions with return values with types std::vector<int>
, std::vector<bool>
, std::vector<double>
. I need to pass variables with these types to Java. So I'm using JNI and my function has return values with types jintArray
, jbooleanArray
, jdoubleArray
.
I'm using following code to convert double
type:
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've no problem with this code block. But when I want to do this for int
and bool
types there is a problem at the following:
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 definitions of jint
and jboolean
, since:
typedef long jint;
typedef unsigned char jboolean;
and for jdouble
:
typedef double jdouble;
As, you can see my convenient solution for double
doesn't work for int
and bool
types since their typedefs doesn't match.
So, my question is how can I do this conversion for all primitive types conveniently?
Thanks in advance
Since the data types might have different sizes you have to copy the vector. The simplest way to do this is
std::vector<jboolean> tmp(data.begin(), data.end());
jboolean *outArray = &tmp[0];
Of course, you can allocate the jBooleanArray
and set the elements in a for loop or write a wrapper for it that behaves like an STL container.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With