[英]convert c++ primitive type vector to java primitive type array
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>
. 我正在为我的项目使用第三方C ++ API,它具有带有返回值的函数,这些返回值的类型为
std::vector<int>
, std::vector<bool>
, std::vector<double>
。 I need to pass variables with these types to Java. 我需要将具有这些类型的变量传递给Java。 So I'm using JNI and my function has return values with types
jintArray
, jbooleanArray
, jdoubleArray
. 所以我使用的是JNI,我的函数具有类型为
jintArray
, jbooleanArray
, jdoubleArray
返回值。
I'm using following code to convert double
type: 我正在使用以下代码转换
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'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: 但是,当我要对
int
和bool
类型执行此操作时,以下内容会出现问题:
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: 问题在于
jint
和jboolean
定义,因为:
typedef long jint;
typedef unsigned char jboolean;
and for jdouble
: 对于
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. 就像您看到的那样,我方便的
double
解决方案不适用于int
和bool
类型,因为它们的typedef不匹配。
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. 当然,您可以分配
jBooleanArray
并在for循环中设置元素,或为其编写包装器,使其表现像STL容器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.