Python C API: 尝试构建字典时出现问题

Python C API: Problems trying to build a dictionary

我正在尝试使用 C API 构建 Python 字典,但似乎不可能(Py_BuildValue returns 一个 NULL 对象)使用PyObject* 作为值。 我的情况如下:

#include <python3.5/Python.h>
...
PyObject *myList = PyList_New(1);
PyList_SetItem(myList, 0, Py_BuildValue("i", 1));
dict = Py_BuildValue("{siso}",
           "anInt", myInt,
           "aList", mylist);

我正在寻找适用于列表通用大小的解决方案。我在 official documentation 中没有找到任何关于此的内容,并且还用谷歌搜索了几个小时。有人可以帮我吗?提前致谢

您使用的格式规范有误。 Here 就是一个例子。

因此,为了构建字典,您可以这样做:

int a_c_int; // 1
PyObject *a_python_list; // [1]
// ...
Py_BuildValue("{s:i,s:O}",  # note the capital O ;)
          "abc", a_c_int, 
          "def", a_python_list);    

returns python 字典

{'abc': 1, 'def': [1]}