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

ljo*_*fre 5 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;
    };
};
Run Code Online (Sandbox Code Playgroud)

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

namespace py = boost::python;

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

Tan*_*ury 5

当类型通过 Boost.Python 公开时,它们被注入到当前作用域中。某些类型,例如用 引入的类型,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
Run Code Online (Sandbox Code Playgroud)

交互式Python:

>>> import example
>>> e = example.Human.Emotion
>>> e
<class 'example.Emotion'>
>>> hasattr(e, 'joy')
True
Run Code Online (Sandbox Code Playgroud)