在C++中调用Python的list,为啥这样转化会报错应该咋解决

谢邀。首先,使用Python API之前需要调用Py_Initialize()其次,Py_BuildValue("s","Test");返回的并不是Tuple,所以不能够用PyArg_ParseTuple解析。在Python的文档中指出:Py_BuildValue() does not always build a tuple. It builds a tuple only if its format string contains two or more format units. If the format string is empty, it returns None; if it contains exactly one format unit, it returns whatever object is described by that format unit. To force it to return a tuple of size 0 or one, parenthesize the format string.由此看,通过PyList_GetItem取回的值也是str类型。既然已经知道了是str类型,那么就用str类型的转换函数即可。#include "Python.h"void main(){ char *x; PyObject *item; PyObject *list; Py_Initialize(); list = PyList_New(0); item = Py_BuildValue("s","Test"); printf("%d\",PyTuple_Check(item)); //0 printf("%d\",PyString_Check(item)); //1 PyList_Append(list,item); item = PyList_GetItem(list,0); printf("%d\",PyTuple_Check(item)); //0 printf("%d\",PyString_Check(item)); //1 x = PyString_AsString(item); printf("%s",x); //Test}
■网友
手头没有运行环境,没办法确定问题,先定位到看哪一行出了问题,感觉是ParseValue那行出了问题


    推荐阅读