2 #include <numpy/arrayobject.h> 17 typedef Eigen::MatrixXd::Scalar T;
19 npy_intp shape[2] = { mat.rows(), mat.cols() };
20 PyArrayObject* pyArray = (PyArrayObject*)
21 PyArray_SimpleNew(2, shape,
24 T* pyData = (T*)PyArray_DATA(pyArray);
25 for(
int i=0;i<mat.rows();++i)
26 for(
int j=0;j<mat.cols();++j)
27 pyData[i*mat.cols()+j] =
mat(i,j);
29 return ((PyObject*)pyArray);
39 bp::converter::registry
40 ::push_back(&convertible,
42 bp::type_id<Eigen::MatrixXd>());
48 typedef Eigen::MatrixXd::Scalar T;
50 if (!PyArray_Check(obj_ptr)) {
53 if (PyArray_NDIM(obj_ptr) > 2) {
59 int flags = PyArray_FLAGS(obj_ptr);
60 if (!(flags & NPY_C_CONTIGUOUS)) {
63 if (!(flags & NPY_ALIGNED)) {
72 bp::converter::rvalue_from_python_stage1_data* memory)
74 typedef Eigen::MatrixXd::Scalar T;
75 using namespace Eigen;
77 PyArrayObject * pyArray =
reinterpret_cast<PyArrayObject*
>(pyObj);
78 int ndims = PyArray_NDIM(pyArray);
81 int dtype_size = (PyArray_DESCR(pyArray))->elsize;
82 int s1 = PyArray_STRIDE(pyArray, 0);
83 assert(s1 % dtype_size == 0);
85 int R = MatrixXd::RowsAtCompileTime;
86 int C = MatrixXd::ColsAtCompileTime;
87 if (R == Eigen::Dynamic) R = PyArray_DIMS(pyArray)[0];
88 else assert(PyArray_DIMS(pyArray)[0]==R);
90 if (C == Eigen::Dynamic) C = PyArray_DIMS(pyArray)[1];
91 else assert(PyArray_DIMS(pyArray)[1]==C);
93 T* pyData =
reinterpret_cast<T*
>(PyArray_DATA(pyArray));
95 void* storage = ((bp::converter::rvalue_from_python_storage<MatrixXd>*)
96 (memory))->storage.bytes;
97 MatrixXd &
mat = * new (storage) MatrixXd(R,C);
100 mat(i,j) = pyData[i*C+j];
102 memory->convertible = storage;
111 Eigen::MatrixXd
mat = Eigen::MatrixXd::Random(5,5);
112 std::cout <<
"EigenMAt = " << mat << std::endl;
118 std::cout <<
"test2: dim = " << mat.rows() <<
" ||| m[0,0] = " <<
mat(0,0) << std::endl;
125 bp::to_python_converter<Eigen::MatrixXd,
129 bp::def(
"test",
test);
130 bp::def(
"test2",
test2);
static void * convertible(PyObject *obj_ptr)
static void construct(PyObject *pyObj, bp::converter::rvalue_from_python_stage1_data *memory)
BOOST_PYTHON_MODULE(libeigenc)
void test2(Eigen::MatrixXd mat)
EigenMatrix_from_python_array()
static PyObject * convert(Eigen::MatrixXd const &mat)