具有关键字参数的PyObject_CallMethod [英] PyObject_CallMethod with keyword arguments

查看:135
本文介绍了具有关键字参数的PyObject_CallMethod的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的C应用程序中嵌入一个Python(2.7)库,并且正在使用Python/C API从C调用Python代码.我需要调用一个带有关键字参数的Python方法.从语义上讲,我正在尝试在Python中达到以下等效行:

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");

我对Python并不十分熟悉,并且由于目前文档尚不完全清楚,而且Google搜索也没有提供很多有用的信息,因此我对此有些犹豫.我将不胜感激.

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.

推荐答案

最后,我使用了 PyObject_Call 可以做到这一点(感谢Bakuriu的提示!).以防万一有人想知道如何做,这是我的代码:

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);

这篇关于具有关键字参数的PyObject_CallMethod的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆