【发布时间】:2019-03-17 18:18:27
【问题描述】:
问题
我正在尝试转换由在 C++ 代码中调用的 python 函数返回的列表列表。尽管 pybind11 库允许从 python 数据类型到 C++ 数据类型的类型转换,但我尝试将 python 返回的列表列表转换为 C++ 字符串的 std::list 或 std::list,每次都失败时间。
代码
这里是python函数(该函数返回一个包含字符串值的列表):
def return_sheet(self):
"""Returns the sheet in a list of lists
"""
dataTable = []
for r in range(self._isheet.nrows):
datalist = []
for c in range(self._isheet.ncols):
datalist.append(self._isheet.cell_value(r,c))
dataTable.append(datalist)
return dataTable
我在这里使用 pybind11 在 C++ 中调用它:
py::list obj = _tool.attr("return_sheet")();
data = py::cast<SheetData>(obj); // This is where the problem lies, This cast crashes the program
其中SheetData 是typedef:
typedef std::list<std::list<std::string> > SheetData;
在调试的时候,我发现程序实际上在这行崩溃了:
py::object dataTable = _tool.attr("return_sheet")(); // Where _tool.attr("return_sheet")() gives an py::object which is a list of list of str
有人知道吗,我怎样才能成功地将 python 列表的列表转换为 C++ 的 std::list 的 std::list?
编辑
这是我在 c++ 中嵌入的 python 程序文件 [xlanalysisr.py] :https://pastebin.com/gARnkMTv
这里是 c++ 代码 [main.cpp]:https://pastebin.com/wDDUB1s4
注意:xlanalysisr.py 中的所有其他函数在嵌入 c++ 时不会导致崩溃 [只有 return_sheet() 函数会导致崩溃]
【问题讨论】:
标签: python c++ python-c-api pybind11