Search code examples
pythonpython-2.7python-c-apipython-embedding

PyObject_CallMethod with keyword arguments


I'm trying to embed a Python (2.7) library in my C application and I'm using the Python/C API to call Python code from C. I need to call a Python method that takes keyword arguments. Semantically, I'm trying to achieve the equivalent of the following line in Python:

myobject.dosomething('blahdy blah', somearg=True)

By reading the documentation, I have managed to get as far as the following, but this doesn't pass in the keyword arguments:

PyObject_CallMethod(myobject, "dosomething", "s", "blahdy blah");

I'm not super familiar with Python and I'm kind of stuck at this point as the documentation is not entirely clear on this and Google searches didn't turn up much useful info either. I'd appreciate any help.


Solution

  • In the end I used PyObject_Call to do this (thanks Bakuriu for the hint!). Just in case anyone wonders how to do that, here's my code:

    PyObject *args = Py_BuildValue("(s)", "blahdy blah");    
    PyObject *keywords = PyDict_New();
    PyDict_SetItemString(keywords, "somearg", Py_True);
    
    PyObject_Call(PyObject_GetAttrString(myobject, "do something"), args, keywords);
    Py_DECREF(args);
    Py_DECREF(keywords);