在boost :: python的类中公开public struct

时间:2013-11-18 04:37:15

标签: c++ python wrapper boost-python

我想在boost :: python

上使用这个C ++类而不是python代码
/* creature.h */
class Human {
private:
public:
    struct emotion {
        /* All emotions are percentages */
        char joy;
        char trust;
        char fear;
        char surprise;
        char sadness;
        char disgust;
        char anger;
        char anticipation;
        char love;
    };
};

问题是如何在boost-python中公开这个公共属性

namespace py = boost::python;

BOOST_PYTHON_MODULE(example)
{
    py::class_<Human>("Human");
        // I have not idea how put the public struct here
}

1 个答案:

答案 0 :(得分:4)

当通过Boost.Python公开类型时,它们会被注入current scope。某些类型(例如与class_一起引入的类型)可用作当前范围。

以下是一个完整的注释示例:

#include <boost/python.hpp>

struct Human
{
  struct emotion
  {
    char joy;
    // ...
  };
};

BOOST_PYTHON_MODULE(example)                     // set scope to example
{
  namespace python = boost::python;
  {
    python::scope in_human =                     // define example.Human and set
      python::class_<Human>("Human");            // scope to example.Human

    python::class_<Human::emotion>("Emotion")    // define example.Human.Emotion
      .add_property("joy", &Human::emotion::joy) 
      ;
  }                                              // revert scope, scope is now
}                                                // example

Interactive Python:

>>> import example
>>> e = example.Human.Emotion
>>> e
<class 'example.Emotion'>
>>> hasattr(e, 'joy')
True