0

I have a real simple Python function:

def myfunc(x): 
    return 2.0 * x 


I want to send this function to a C++ program and call it so I have done this:

#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);
}


My Python program works correctly:

from C_API_Test import execMyPyFunc
def myfunc(x): 
    return 2.0 * x
fx = execMyPyFunc(1.28,myfunc)
print fx


What I would like to do though is to somehow get the pointer from my Python function (PyObject *Fx) and pass this to a C++ function expecting: double(*fx)(double). Does anyone know how to do this (if possible)? I tried to initialize double(*cFx)(double) and cast my Python function as cFx = (double(*)(double))Fx but this does not work. Any ideas?

4

1 回答 1

1

您将无法像那样简单地将 Python 函数转换为 C。

而是传递 PyObject 函数指针,调用函数,然后转换为 C double。此代码将-1在失败时返回。

static double cFx(PyObject *fx, double x){
    PyObject *pyresult = PyObject_CallFunction(fx, "d", x);
    if (pyresult == NULL) return -1;
    double cppresult = PyFloat_AsDouble(pyresult);
    Py_DECREF(pyresult);
    if (PyErr_Occurred()) return -1;
    return cppresult;
}

重要的部分是将引用计数减少到返回值,PyObject_CallFunction因为您没有将它传递给 Python 解释器来处理。

于 2013-08-26T18:31:08.063 回答