2

我正在尝试使用 C API 构建 Python 字典,但似乎不可能(Py_BuildValue 返回一个 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);

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

4

1 回答 1

5

您使用了错误的格式规范。是一个例子。

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

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

返回 python 字典

{'abc': 1, 'def': [1]}
于 2018-08-01T11:58:16.670 回答