PyObject_CallMethod with keyword arguments

半城伤御伤魂 提交于 2019-12-03 13:46:06

Tamas's answer will get the job done, but it will also leak memory. To avoid leaks, use

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

PyObject *result = PyObject_Call(myobject_method, args, keywords);
Py_DECREF(args);
Py_DECREF(keywords);
Py_DECREF(myobject_method);

// Do something with the result

Py_DECREF(result);

Of course, if there are any errors or exceptions in the Python code some of the PyObjects will be NULL and your program will probably crash. Checking for NULL results and/or using Py_DECREFX() can help you avoid this.

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!