0

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

1
  • You can use PyCFunction (create it with PyCFunction_New) - you may need to wrap your "raw" C function with something that has the appropriate signature (accepting PyObject*). That's less convenient if you need it to be dynamic though, because you need to worry about the lifetime of the PyMethodDef then Commented Jul 27, 2024 at 18:54

1 Answer 1

0

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 );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.