当前位置:  开发笔记 > 编程语言 > 正文

CPython - 读取C函数内的Python字典(键/值)作为参数传递

如何解决《CPython-读取C函数内的Python字典(键/值)作为参数传递》经验,为你挑选了1个好方法。

我正在编写Python C扩展.我正在将Python Dictionary传递给C函数.我可以使用以下代码解析它:

PyObject *large_dict = NULL;
if (! PyArg_ParseTuple( args, "O!", &PyDict_Type, &large_dict)) return NULL;
if (large_dict != NULL)
{
   printf("Large Dictionary Not Null\n");
}

这里打印了"Large Dictionary Not Null"语句,这意味着字典被成功解析.现在我想通过指定键来访问字典值,就像在python中一样.即dict ['k1'],这给出了值v1.

如何访问此C函数中的字典键/值?

请建议我一个解决方案?



1> Aashish P..:

您应该浏览以下链接,https: //docs.python.org/2/c-api/dict.html摘录,

PyObject* PyDict_GetItem(PyObject *p, PyObject *key)
Return value: Borrowed reference.
Return the object from dictionary p which has a key key. Return NULL if the key key is not present, but without setting an exception.

PyObject* PyDict_GetItemString(PyObject *p, const char *key)
Return value: Borrowed reference.
This is the same as PyDict_GetItem(), but key is specified as a char*, rather than a PyObject*.

PyObject* PyDict_Items(PyObject *p)
Return value: New reference.
Return a PyListObject containing all the items from the dictionary, as in the dictionary method dict.items().

PyObject* PyDict_Keys(PyObject *p)
Return value: New reference.
Return a PyListObject containing all the keys from the dictionary, as in the dictionary method dict.keys().

PyObject* PyDict_Values(PyObject *p)
Return value: New reference.
Return a PyListObject containing all the values from the dictionary p, as in the dictionary method dict.values().

留意borrowed reference / new reference.编写Python扩展时有点棘手.

推荐阅读
yzh148448
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有