pythoncpythonpython-c-api

Create a PyObject with a pointer to a C function


Let's say I have this Python function:

def foo(bar):
    bar()

And this C function

void bar() {
}

How can I create a PyObject with Python C API that holds a pointer to bar function so I can call the Python function. Something like this

PyObject* function = PyObject_GetAttrString(module, "foo");
// how to create PyObject* args?
PyObject* result = PyObject_Call(function, args, NULL);

Searched and read the docs, but can not find a similar example


Solution

  • Thanks to DavidW for the hint, here is a working example how to set a void bar method with no parameters defined is some Python module

    static PyObject* bar(PyObject* self, PyObject* args)
    {
        return PyNone;
    }
    
    static PyMethodDef bar_func_def = {
        "bar",
        bar,
        METH_NOARGS,
        "docstrings go here"
    };
    
    PyObject* function_arg = PyCFunction_NewEx(&bar_func_def, pymodule, PyUnicode_FromString("pymodule"));
    PyObject_SetAttrString(pymodule, "bar", function_arg );