los*_*yzd 10 c++ python boost boost-python
假设我想获得一些全局/内部c ++对象的引用,一种方法是声明函数boost::python::return_value_policy<reference_existing_object>().
两者GetGlobalObjectA并GetGlobalObjectB返回对原始c ++对象的引用,而不创建新副本;
但是如何GetGlobalObjectByID返回对现有c ++对象的引用?
struct A { uint32_t value; };
struct B { uint64_t value; };
A globalA;
B globalB;
boost::python::object GetGlobalObjectByID(int id)
{
// boost::python::object will return a new copy of C++ object, not the global one.
if (id == 1)
return boost::python::object(&globalA);
else if (id == 2)
return boost::python::object(&globalB);
else
return boost::python::object(nullptr);
}
A& GetGlobalObjectA() { return globalA; }
B& GetGlobalObjectB() { return globalB; }
BOOST_PYTHON_MODULE(myModule)
{
using namespace boost::python;
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转换器。
模板 <类型名称 T>
内联对象 MagicMethod(T* ptr)
{
类型名reference_existing_object::apply::类型转换器;
句柄句柄(转换器(ptr));
返回对象(句柄);
}
这是修改后的版本。
boost::python::object GetGlobalObjectByID(int id)
{
如果(id==1)
返回 MagicMethod(&globalA);
否则如果(id == 2)
返回 MagicMethod(&globalB);
别的
返回升压:python::object();
}
| 归档时间: |
|
| 查看次数: |
593 次 |
| 最近记录: |