Boost.Python 返回引用现有 c++ 对象的 python 对象

Boost.Python return python object which references to existing c++ objects

本文关键字:对象 c++ python Python 返回 引用 Boost      更新时间:2023-10-16

假设我想获取对某个全局/内部c ++对象的引用,一种方法是用boost::python::return_value_policy<reference_existing_object>()声明函数。

GetGlobalObjectAGetGlobalObjectB都返回对原始 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_&ltA>("A"); class_&ltB>("B"); def("GetGlobalObjectByID", GetGlobalObjectByID); def("GetGlobalObjectA", GetGlobalObjectA, return_value_policy&ltreference_existing_object>()); def("GetGlobalObjectB", GetGlobalObjectB, return_value_policy&ltreference_existing_object>()); }

基于这个答案,我发现可以使用reference_existing_object::apply作为转换器。

模板 &lttypename 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(); }