Build a PyObject* from a C function?

后端 未结 1 1624
陌清茗
陌清茗 2021-01-02 02:35

I am embedding Python in a C++ library which I am making. I would like users to be able to pass C functions in the form of function pointers PyObject* (fpFunc*)(PyObje

1条回答
  •  鱼传尺愫
    2021-01-02 03:06

    Found it. Though it's not in the docs and it's hardly explicit in the source.

    PyObject* (*fpFunc)(PyObject*,PyObject*) = someFunction;
    PyMethodDef methd = {"methd",fpFunc,METH_VARARGS,"A new function"};
    PyObject* name = PyString_FromString(methd.ml_name);
    PyObject* pyfoo = PyCFunction_NewEx(&methd,NULL,name);
    Py_DECREF(name);
    

    It works. I can call the function like I normally would call a Python function object.

    If you're curious, all I found in the doc was about Py_InitModule4 and loading modules, so I went to check Python's source, and found out about PyCFunction, then I looked around in the doc but I couldn't find anything about PyCFunction_NewEx, so I had to check the source to make sure it was as I thought.

    0 讨论(0)
提交回复
热议问题