当前位置:   article > 正文

python调用函数库_在Python中调用EGIN库函数调用C++

python import eigen

如果使用不同语言编写的数字模块接口,最好保持交换的数据尽可能平坦。在

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是否对此有足够的支持。在

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/106662
推荐阅读
相关标签
  

闽ICP备14008679号