【发布时间】:2013-08-26 17:22:26
【问题描述】:
我有一个真正简单的 Python 函数:
def myfunc(x):
return 2.0 * x
我想将此函数发送到 C++ 程序并调用它,所以我这样做了:
#include "Python.h"
static PyObject *execMyPyFunc(PyObject *self, PyObject *args) {
PyObject *Fx, *pyresult;
double x;
PyArg_ParseTuple(args, "dO", &x, &Fx);
pyresult = PyObject_CallFunction(Fx, "d", x);
return pyresult;
}
static PyMethodDef C_API_TestMethods[] = {
{"execMyPyFunc", execMyPyFunc, METH_VARARGS, "Add documentation here.."},
{NULL, NULL}
};
PyMODINIT_FUNC initC_API_Test(void) {
Py_InitModule("C_API_Test", C_API_TestMethods);
}
我的 Python 程序运行正常:
from C_API_Test import execMyPyFunc
def myfunc(x):
return 2.0 * x
fx = execMyPyFunc(1.28,myfunc)
print fx
不过,我想做的是以某种方式从我的 Python 函数 (PyObject *Fx) 中获取指针,并将其传递给期望的 C++ 函数:double(*fx)(double)。有谁知道如何做到这一点(如果可能的话)?我尝试初始化 double(*cFx)(double) 并将我的 Python 函数转换为 cFx = (double(*)(double))Fx 但这不起作用。有什么想法吗?
【问题讨论】:
-
你看Boost.Python了吗?
-
是的,但是如果没有 Boost、SWIG 等,如何做到这一点。
标签: c++ python c api python-c-api