You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Pybind11将std::list<int>绑定为Python类型

如何用Pybind11绑定std::list类型?

按照Pybind11文档所述,绑定STL容器可采用如下方式:

#include <pybind11/stl_bind.h>
#include <pybind11/stl.h>

PYBIND11_MAKE_OPAQUE(std::vector<int>);
    
// 后续绑定代码中:
py::bind_vector<std::vector<int>>(m, "VectorInt");

通过上述定义,我可以轻松封装返回std::vector<int>的函数并在Python中调用。但问题在于,若函数返回std::list<int>,该如何将此类型引入Pybind11?似乎不存在py::bind_list<std::list<int>>方法,尝试用bind_vector绑定:

py::bind_vector<std::list<int>>(py_module, "ListInt", pybind11::module_local(false));

会出现编译错误,提示指定类型并非std::vector。若不进行该定义,在Python中调用方法时会报错:

>>> l = returnIntList(3)
TypeError: Unregistered type : std::list<int,std::allocator<int> >

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Unable to convert function return value to a Python type! The signature was
        (arg0: int) -> std::list<int,std::allocator<int> >

我是否遗漏了文档中的某些内容?另外,在Pybind库关于绑定和STL容器的自动化测试中,未见到以std::list作为返回值的示例。


内容的提问来源于stack exchange,提问作者TonySalimi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 18:20:02