Boost.Python 返回引用现有 c++ 对象的 python 对象
Boost.Python return python object which references to existing c++ objects
假设我想获取对某个全局/内部c ++对象的引用,一种方法是用boost::python::return_value_policy<reference_existing_object>()
声明函数。
GetGlobalObjectA
和GetGlobalObjectB
都返回对原始 c++ 对象的引用,而不创建新副本;
但是如何使GetGlobalObjectByID
向现有c ++对象返回引用呢?
结构体 A { uint32_t 值; }; 结构体 B { uint64_t 值; }; 一个全球A; B 全球 B; boost::p ython::object GetGlobalObjectByID(int id) { boost::p ython::object 将返回C++对象的新副本,而不是全局副本。 if (id == 1) return boost::p ython::object(&globalA); 否则如果 (id == 2) return boost::p ython::object(&globalB); 还 返回提升::p ython::object(nullptr); } A& GetGlobalObjectA() { return globalA; } B& GetGlobalObjectB() { return globalB; } BOOST_PYTHON_MODULE(我的模块) { 使用命名空间提升::p ython; class_<A>("A"); class_<B>("B"); def("GetGlobalObjectByID", GetGlobalObjectByID); def("GetGlobalObjectA", GetGlobalObjectA, return_value_policy<reference_existing_object>()); def("GetGlobalObjectB", GetGlobalObjectB, return_value_policy<reference_existing_object>()); }
基于这个答案,我发现可以使用reference_existing_object::apply
作为转换器。
模板 <typename T> 内联对象魔术方法(T* ptr) { 类型名称 reference_existing_object::应用::类型转换器; 手柄手柄(转换器); 返回对象(句柄); }
这是修改后的版本。
boost::p ython::object GetGlobalObjectByID(int id) { if (id == 1) 返回 MagicMethod(&globalA); 否则如果 (id == 2) 返回 MagicMethod(&globalB); 还 返回 boost:python::object(); }
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- 使用"std::unordereded_map"映射到"std::list"对象