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

如何在nanobind中实现Boost.Python manage_new_object的等价功能?

在nanobind中让Python管理堆分配裸指针的生命周期

nanobind 提供了和 Boost.Python 中 manage_new_object 完全对应的机制,核心是**nb::take_ownership** 返回值策略——它会让 Python 接管裸指针指向的堆内存所有权,当对应的 Python 对象被垃圾回收时,自动调用 delete 释放内存。

基础用法示例

假设你有一个返回堆分配裸指针的 C++ 函数:

MyClass* create_my_class() {
    return new MyClass();
}

在 nanobind 中包装时,只需在绑定函数时指定该返回值策略:

#include <nanobind/nanobind.h>
namespace nb = nanobind;

NB_MODULE(my_module, m) {
    m.def("create_my_class", &create_my_class, nb::return_value_policy(nb::take_ownership));
}

自定义销毁逻辑的场景

如果你的对象是通过自定义分配器创建的(无法用默认 delete 释放),可以搭配 nb::destructor 参数指定自定义销毁函数:

// 自定义创建和销毁函数
CustomObj* create_custom_obj() {
    return custom_new();
}

void destroy_custom_obj(CustomObj* obj) {
    custom_delete(obj);
}

// nanobind绑定
NB_MODULE(my_module, m) {
    m.def("create_custom_obj", &create_custom_obj,
          nb::return_value_policy(nb::take_ownership),
          nb::destructor(&destroy_custom_obj));
}

内容的提问来源于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:11