0
我有一個真正簡單的Python功能:
調用C中的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](http://www.boost.org/doc/libs/1_54_0/libs/python/doc/tutorial/doc/html/python/object.html#python.creating_python_object )? – P0W
是的,但是如何在沒有Boost,SWIG等的情況下做到這一點 –