pybind 如何对 py::list 对象进行操作

pybind how can I operate over a py::list object

本文关键字:对象 操作 list pybind py      更新时间:2023-10-16

为了更好地理解如何使用pybind库将参数从Python传递到C++函数,我想构建一个小的虚拟/演示代码,我可以在其中接收C++端的Python列表,将其转换为浮点指针对象,然后打印它。

虽然我知道我可以使用py::list类,但我还没有弄清楚这个类可用的方法。我查看了文档参考,然后查看了代码(list.h,stl.h(,但无法弄清楚哪些方法可用。

什么相当于__getitem__?我有可用的所有 python 方法吗py::list

您正在寻找的代码在这里:

class list : public object {
public:
PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List)
explicit list(size_t size = 0) : object(PyList_New((ssize_t) size), stolen_t{}) {
if (!m_ptr) pybind11_fail("Could not allocate list object!");
}
size_t size() const { return (size_t) PyList_Size(m_ptr); }
detail::list_accessor operator[](size_t index) const { return {*this, index}; }
detail::list_iterator begin() const { return {*this, 0}; }
detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; }
template <typename T> void append(T &&val) const {
PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());
}
};

还要记住,py::list继承自py::object,而又继承自py::handle(这也意味着您是通过引用传递的(。根据我的经验,这种用法的文档很少,阅读代码是你最好的选择。

我们可以从类定义中看到,我们可以使用成员函数sizeoperator[]beginend(C++迭代器!(和append(模板化!(。如果这还不够,您可以使用attr来访问 python 属性(包括方法(。下面是一个示例:

Python 代码 (some_python.py(:

import cppimport
cpp = cppimport.imp("some_cpp")
l = [1,2,3,4,5]
cpp.test(l)
print('after C++', l)
cpp.float_cast(l)

C++代码 (some_cpp.cpp(:

/* <%
setup_pybind11(cfg)
%> */
#include <pybind11/pybind11.h>
#include <iostream>
#include <string>
namespace py = pybind11;
void test(py::list l) {
l.attr("pop")();
std::cout << "List has length " << l.size() << std::endl;
for (py::handle obj : l) {  // iterators!
std::cout << "  - " << obj.attr("__str__")().cast<std::string>() << std::endl;
}
l.append(10);  // automatic casting (through templating)!
}
void float_cast(py::list l) {
float f = l.cast<float>();
}
PYBIND11_MODULE(some_cpp, m) {
m.def("test", &test);
m.def("float_cast", &float_cast);
}

输出:

List has length 4
- 1
- 2
- 3
- 4
after C++ [1, 2, 3, 4, 10]
Traceback (most recent call last):
File "some_python.py", line 9, in <module>
cpp.float_cast(l)
RuntimeError: Unable to cast Python instance to C++ type (compile in debug mode for details)

如您所见,我还包括了您投射到浮标的具体问题。在这里,我使用了cast方法py::handle,这是一个很好的例外。您可以尝试"直接"投射对象(例如float* f = (float*) &l;(,但这会给您带来垃圾,我想这不是您要找的。

还有一点要注意:pybind/stl.h支持Python的标准类型和C++版本之间的转换。例如,一个list可以转换为一个std::vector<int>,包括类型检查。这样做的一个重要效果是数据作为副本而不是引用传递。