expose public struct inside a class for boost::python

boost-python, c++, python, wrapper

Solution

When types are exposed through Boost.Python, they are injected into the current scope. Some types, such as those introduced with `class_`, can be used as the current scope.

Here is a complete annotated example:

#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

Problem

I want to use this C++ class over python code with boost::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; }; }; ``` the question is how to expose this public attribute in boost-python ``` namespace py = boost::python; BOOST_PYTHON_MODULE(example) { py::class_<Human>("Human"); // I have not idea how put the public struct here } ```

Original source