I tried reproducing some of the examples described here, but I experience the following problem with the code below, which was written by just copy-pasting relevant parts of the linked page.
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
#include <iostream>
using namespace std;
namespace p = boost::python;
namespace np = boost::python::numpy;
np::ndarray test()
{
int data[] = {1,2,3,4,5};
p::tuple shape = p::make_tuple(5);
p::tuple stride = p::make_tuple(sizeof(int));
p::object own;
np::dtype dt = np::dtype::get_builtin<int>();
np::ndarray array = np::from_data(data, dt, shape,stride,own);
std::cout << "Selective multidimensional array :: "<<std::endl
<< p::extract<char const *>(p::str(array)) << std::endl ;
return array;
}
BOOST_PYTHON_MODULE(test_module)
{
using namespace boost::python;
// Initialize numpy
Py_Initialize();
boost::python::numpy::initialize();
def("test", test);
}
When I compile as a shared library and load the module in python,
import test_module as test
print(test.test())
it seems that the ndarray
gets created properly by the C++ code, but the version that python receives is rubbish; the arrays that get printed are:
[1 2 3 4 5]
[2121031184 32554 2130927769 32554 0]
What could be the cause of such a difference?