python - 如何阻止 pybind11 释放由 Python 构造的对象?
问题描述
所以,我知道 pybind 可以让你为你封装的方法设置一个返回值策略。但是,当我尝试在构造函数上使用此策略时,这似乎对我不起作用。我有一个类来包装我的 C++ 类型,如下所示:
class PyComponent{
public:
static Component* Create(ComponentType type) {
Component* c = new Component(type);
// Irrelevant stuff removed here
return c;
}
/// @brief Wrap a behavior for Python
static void PyInitialize(py::module_& m);
};
void PyComponent::PyInitialize(py::module_ & m)
{
py::class_<Component>(m, "Component")
.def(py::init<>(&PyComponent::Create), py::return_value_policy::reference)
;
}
Component()
但是,如果我调用并且创建的对象超出范围,这不会阻止我的 Component 类型从 Python 端释放。有什么建议么?
解决方案
我确实想出了解决方案。这是传递py::nodelete
给我的班级的包装器
void PyComponent::PyInitialize(py::module_ & m)
{
py::class_<Component, std::unique_ptr<Component, py::nodelete>>(m, "Component")
.def(py::init<>(&PyComponent::Create), py::return_value_policy::reference)
;
}
推荐阅读
- python - python/beautifulsoup:查找具有特定属性的上一行
- java - spring-cloud-gateway 路径路由谓词不接受“/”
- python - 在 Python 中解析逻辑 JSON 数据
- reactjs - 在 React 中使用 TypeScript 时“this.state”从何而来
- python - Discord Bot 不响应命令
- encryption - 当密钥具有特定长度(以位为单位)时,这意味着什么?
- python - 如何(有效地)找到足够有效数字所需的最小序列长度?
- mysql - 仅使用 xamarin Andriod 连接到 mySQL 数据库时出现问题,但在 iOS 和 UWP 中有效
- swiftui - SwiftUI 不发布模型实例
- python - 修改 YAML 内容