赞
踩
如果使用不同语言编写的数字模块接口,最好保持交换的数据尽可能平坦。在
libeigen实矩阵的最平坦表示是实型的c数组(float或double)
下面是一个C++¹示例#include
#include
#include
#include
#include
#include
using std::size_t;
typedef double real_t;
typedef Eigen::Matrix
Matrix;
static PyObject* p_eigen_python_error(NULL);
static PyObject *
randomDxDMatrix(PyObject *self, PyObject *args) {
PyObject* p(NULL);
PyObject* item(NULL);
try{
size_t d(0);
PyArg_ParseTuple(args, "L", &d);
Matrix M = Matrix::Random(d,d);
size_t length = d * d;
p = PyList_New(length);
if (p == NULL) {
std::stringstream msg;
msg << "Could not allocate a Pylist of "
<< d << "x" << d << " = " << d*d
<< " size for the return Object";
throw std::runtime_error(msg.str().c_str());
} else {
for (size_t i = 0; i < length; ++i) {
item = PyFloat_FromDouble(M.data()[i]);
PyList_SET_ITEM(p, i, item);
}
}
} catch (const std::exception& e) {
delete p; p = NULL;
delete item; item = NULL;
std::string msg = ("randomDxDMatrix failed: ");
msg += e.what();
PyErr_SetString(p_eigen_python_error, msg.c_str());
}
return p;
}
static PyMethodDef EigenMethods[] = {
{"randomDxDMatrix", randomDxDMatrix, METH_VARARGS,
"Gets a random DxD matrix column-major as a list of (python) floats"},
{NULL, NULL, 0, NULL} /* Sentinel */
};
PyMODINIT_FUNC
initeigen_python(void) {
PyObject* p;
p = Py_InitModule("eigen_python", EigenMethods);
if (p == NULL)
return;
p_eigen_python_error = PyErr_NewException(
const_cast("eigen_python.error"),
NULL, NULL
);
Py_INCREF(p_eigen_python_error);
PyModule_AddObject(p, "error", p_eigen_python_error);
}
这是设置特征_python.py在
^{pr2}$
被用作python2.7 setup_eigen_python.py install user
这是一个小小的试驾import eigen_python as ep
import numpy as np
DIM = 4
M = np.array(ep.randomDxDMatrix(DIM), order="F")
M.shape= DIM,DIM
print(M)
特别是,但迄今为止还没有限制,因为必须在没有提升的情况下相处,所以最好使用C++ 2011标准的特性,如^ {< CD1>}和^ {CD2>},但我不知道QO是否对此有足够的支持。在
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。