You have a C++ std::vector and you want to convert it to a Boost.Python Numpy ndarray.
But, once the ndarray got, you want to get back to the C++ array.
How to do that?
Let's see that in this Boost.Python tutorial.
We need to install Python 3 and Boost on your computer.
So in order to have the exact same software and libraries installed in the exact same locations, I suggest to follow the 2 following tutorials:
In order to use data, from a standard C++ vector to a Numpy ndarray, we need to get the address of the first element in this vector.
The reason is that we are going to use the from_data() method to transform our C++ vector to a Python array.
And this from_data() method needs the address of the first element of an array.
So it would have been possible to use the following:
But we will prefer using:
Once we have our C++ array, it's quite easy to convert it into a Numpy ndarray.
In the from_data() method we'll set the
strides with: python::make_tuple(sizeof(float) * 0, sizeof(float) * 1)
In this example:
Then
So to get the number of elements in the ndarray we can use shape(1) because it holds the size of the vector.
Once we get an ndarray, if we want to come back to a C++ array, we have to use the reinterpret_cast expression.
Indeed, the ndarray::get_data() method returns a char*.
So we use this mechanism to tranform this char* into the type of our choice.
In our case into a float*.
Then with this float* we can do whatever we want.
In the example we modify data from the C++ array by dividing all elements by 10.
And as the ndarray passed as parameter is a pointer, so the original ndarray is also modified.
In bonus, we check with the Boost.Python contains() method if a float is present in the final array.
As a result you'll have from the console:
sizeOfArray = 5 C++ array: 1.5 2.5 3.5 4.5 5.5 py_array: [[1.5 2.5 3.5 4.5 5.5]] C++ array: 0.15 0.25 133.74 0.45 0.55 py_array: [[ 0.15 0.25 133.74 0.45 0.55]] C++ array: 0.15 0.25 133.74 911 0.55 py_array: [[1.5000e-01 2.5000e-01 1.3374e+02 9.1100e+02 5.5000e-01]] py_array: False py_array: True
You are now able to manipulate C++ vector, array and Numpy ndarray like if they were the same object.
Good job, you did it.
Add new comment