在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那行出了问题
推荐阅读
- 怎样成为一名合格的Python程序员?
- python 爬虫,咋获得输入验证码之后的搜索结果
- 非计算机专业想要利用课余时间深入自学C++,想要找到比较体面的工作大概需要啥水平
- python的html5lib这个库咋使用啊我在网上也没有找到相关文档
- 零基础入门学习啥语言好
- Java工程师和C++工程师在工作上有啥区别哪个更适合自身发展
- Python3.4和3.5区别大么
- python 中 def_():...... return _有啥作用
- 新互联网网站用Java还靠谱么对比Php,Python,Ruby的话
- 30岁男,创业失败转行学python,是否很晚?也不好找工作?
