创建一个具有调用策略的属性- boost::python

Create a property with a call policy - boost::python

本文关键字:策略 属性 boost python 调用 一个 创建      更新时间:2023-10-16

我有以下c++类,我想把它们暴露给python。

class PlainOldData
{
     ...
};
class FancyClass
{
public:
    const PlainOldData& GetMyPOD() {return myPOD;}
private:
    PlainOldData myPOD;
};

因为我想让我的python类是python的,我想把myPOD作为一个属性公开。但是,当我尝试执行以下操作时:

// expose with boost::python
BOOST_PYTHON_MODULE(mymod)
{
    class_<PlainOldData>("PlainOldData", init<>());
    // this fails
    class_<FancyClass>("FancyClass", init<>())
        .add_property("myPOD", &FancyClass::GetMyPOD);
}
我得到以下错误:error C2027: use of undefined type 'boost::python::detail::specify_a_return_value_policy_to_wrap_functions_returning<T>'

但是,如果我尝试指定调用策略,例如:

    class_<FancyClass>("FancyClass", init<>())
        .add_property("myPOD", &FancyClass::GetMyPOD, return_value_policy<copy_const_reference>());

我得到一个非常长的错误信息。

是否可以将此函数作为属性公开;我做错了什么吗?

与Python的property()传递Python可调用对象的方式类似,boost::python::class_::add_property()函数可以接受可以用CallPolicies创建的Python可调用对象,例如从boost::python::make_function()返回的对象。

例如,原始代码中的属性可以公开为:
class_<FancyClass>("FancyClass", init<>())
  .add_property("myPOD", make_function(&FancyClass::GetMyPOD,
    return_value_policy<copy_const_reference>()));

下面是一个完整的最小示例:

#include <boost/python.hpp>
class egg {};
class spam
{
public:
  const egg& get_egg() { return egg_; }
private:
  egg egg_;
};
BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  python::class_<egg>("Egg");
  python::class_<spam>("Spam")
    .add_property("egg", python::make_function(&spam::get_egg,
      python::return_value_policy<python::copy_const_reference>()))
    ;
}
互动用法:

>>> import example
>>> spam = example.Spam()
>>> assert(spam.egg is not spam.egg) # unique identities as spam.egg
                                     # returns a copy
>>> egg1 = spam.egg
>>> assert(egg1 is not spam.egg)
>>> egg2 = spam.egg
>>> assert(egg1 is not egg2)