我正在编写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函数中的字典键/值?
请建议我一个解决方案?
您应该浏览以下链接,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扩展时有点棘手.