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

这篇博客介绍了一个C++扩展模块,用于在Python中通过Eigen库生成随机实对称矩阵。代码展示了如何将C++的Eigen矩阵转换为Python的浮点数列表,并处理可能出现的异常。该模块使用了C++11标准,并且与Python2.7兼容。
摘要由CSDN通过智能技术生成

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值