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

如何在nanobind中封装std::vector<T>?附boost::python实现参考

在nanobind中封装std::vector的实现方式

nanobind针对STL容器提供了更简洁的封装方案,无需像Boost.Python那样依赖vector_indexing_suite,具体有两种实现方式:

方式一:使用内置stl_vector快速封装

nanobind的<nanobind/stl/vector.h>头文件提供了nb::stl_vector模板,会自动为std::vector<T>生成Python友好的接口,包含索引访问、长度获取、元素添加/修改/删除等常用方法。

实现代码如下:

#include <nanobind/nanobind.h>
#include <nanobind/stl/vector.h>

namespace nb = nanobind;

void init_my_module(nb::module_ &m) {
    // 封装std::vector<T>,暴露为Python中的"T"类
    nb::stl_vector<T>(m, "T");
}

NB_MODULE(my_module, m) {
    init_my_module(m);
}

方式二:手动定制接口(按需扩展)

如果需要对接口进行精细控制,比如添加自定义方法、限制默认方法,可以通过nb::class_手动注册:

#include <nanobind/nanobind.h>
#include <vector>

namespace nb = nanobind;

void init_my_module(nb::module_ &m) {
    nb::class_<std::vector<T>>(m, "T")
        // 默认构造函数
        .def(nb::init<>())
        // 拷贝构造函数
        .def(nb::init<const std::vector<T>&>())
        // 支持len()调用
        .def("__len__", &std::vector<T>::size)
        // 索引读访问,超出范围抛出索引错误
        .def("__getitem__", [](const std::vector<T>& vec, size_t idx) {
            if (idx >= vec.size()) {
                throw nb::index_error("vector index out of range");
            }
            return vec[idx];
        })
        // 索引写访问
        .def("__setitem__", [](std::vector<T>& vec, size_t idx, const T& val) {
            if (idx >= vec.size()) {
                throw nb::index_error("vector index out of range");
            }
            vec[idx] = val;
        })
        // 添加元素方法(对应Python的append)
        .def("append", &std::vector<T>::push_back)
        // 清空容器
        .def("clear", &std::vector<T>::clear)
        // 按需添加其他方法,比如erase、insert等
        ;
}

NB_MODULE(my_module, m) {
    init_my_module(m);
}

注意事项

  • 替换代码中的T为实际需要封装的类型(如int、std::string或自定义类),若T是自定义类型,需先完成该类型的Python绑定注册。
  • 编译时需确保链接nanobind库,并配置正确的编译选项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 19:43:27