I am working on a project where I need to convert an ndarray
in Python to a vector
in C++ and then return a processed vector
from C++ back to Python in an ndarray
. I am using Boost.Python with its NumPy extension. My problem specifically lies in converting from ndarray
to vector
, as I am using an extended class of vector:
class Vector
{
public:
Vector();
Vector(double x, double y, double z);
/* ... */
double GetLength(); // Return this objects length.
/* ... */
double x, y, z;
};
The ndarray
I receive is n
x2
and filled with x,y data. Then I process the data in C++ with a function, which returns an std::vector<Vector>
. This vector then should be returned to Python as an ndarray
, BUT only with the x and y values.
I have written the following piece of code, with inspiration from "how to return numpy.array from boost::python?" and the gaussian.cpp from the Boost NumPy examples.
#include <vector>
#include "Vector.h"
#include "ClothoidSpline.h"
#include <boost/python/numpy.hpp>
namespace py = boost::python;
namespace np = boost::python::numpy;
std::vector<Vector> getFineSamples(std::vector<Vector> data)
{
/* ... */
}
np::ndarray wrapper(np::ndarray const & input)
{
std::vector<Vector> data;
/* Python ndarray --> C++ Vector */
Py_intptr_t const* size = input.get_shape();
Py_intptr_t const* strides = input.get_strides();
double x;
double y;
double z = 0.0;
for (int i = 0; i < size[0]; i++)
{
x = *reinterpret_cast<double const *>(input.get_data() + i * strides[0] + 0 * strides[1]);
y = *reinterpret_cast<double const *>(input.get_data() + i * strides[0] + 1 * strides[1]);
data.push_back(Vector::Vector(x,y,z));
}
/* Run Algorithm */
std::vector<Vector> v = getFineSamples(data);
/* C++ Vector --> Python ndarray */
Py_intptr_t shape[1] = { v.size() };
np::ndarray result = np::zeros(2, shape, np::dtype::get_builtin<std::vector<Vector>>());
std::copy(v.begin(), v.end(), reinterpret_cast<double*>(result.get_data()));
return result;
}
EDIT: I am aware that this is a (possibly) failed attempt, and I am more interested in a better method to solve this problem, than edits to my code.
So to sum up:
- How do I convert an
boost::python::numpy::ndarray
to astd::vector<Vector>
? - How do I convert a
std::vector<Vector>
to anboost::python::numpy::ndarray
, returning only x and y?
As a last note: I know almost nothing about Python, and I am beginner/moderate in C++.