gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:06:54 24 4
gpt4 key购买 nike

我正在编写一个 Python C 扩展。我正在将 Python dict 传递给 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 中所做的那样。例如,large_dict['k1'] 会给出值 v1

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

最佳答案

你应该通过链接,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().

密切关注借用的引用/新引用。为 Python 扩展编写代码时有点棘手。

关于python - CPython - 在作为参数传递的 C 函数中读取 Python 字典(键/值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34450454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com