PyBind11全球级枚举

时间:2017-12-19 19:20:20

标签: c++11 enums pybind11

PyBind11文档讨论了如何使用enum here

显示的示例假定枚举嵌入在类中,如下所示:

struct Pet {
    enum Kind {
        Dog = 0,
        Cat
    };

    Pet(const std::string &name, Kind type) : name(name), type(type) { }

    std::string name;
    Kind type;
};

py::class_<Pet> pet(m, "Pet");

pet.def(py::init<const std::string &, Pet::Kind>())
    .def_readwrite("name", &Pet::name)
    .def_readwrite("type", &Pet::type);

py::enum_<Pet::Kind>(pet, "Kind")
    .value("Dog", Pet::Kind::Dog)
    .value("Cat", Pet::Kind::Cat)
    .export_values();

我的情况不同。我有一个全局enum,其值用于改变几个函数的行为。

enum ModeType {
  COMPLETE,
  PARTIAL,
  SPECIAL
};

std::vector<int> Munger(
  std::vector<int> &data,
  ModeType          mode
){
  //...
}

我试图像这样注册:

PYBIND11_MODULE(_mlib, m) {
  py::enum_<ModeType>(m, "ModeType")
    .value("COMPLETE", ModeType::COMPLETE )
    .value("PARTIAL",  ModeType::PARTIAL  )
    .value("SPECIAL",  ModeType::SPECIAL  )
    .export_values();

  m.def("Munger",              &Munger, "TODO");
}

编译成功并且模块在Python中加载,但我没有在模块名称中看到ModeType。

我该怎么办?

1 个答案:

答案 0 :(得分:2)

以下示例适合我。就像在我的评论中一样,我使用了&#34; unscoped enum&#34; (github.com/pybind/pybind11/blob/master/tests/test_enum.cpp)。

我可以像这样使用它

import pybind11_example as ep
ep.mood(ep.Happy)

代码:

#include <pybind11/pybind11.h>

enum Sentiment {
    Angry = 0,
    Happy,
    Confused
};

void mood(Sentiment s) {
};

namespace py = pybind11;

PYBIND11_MODULE(pybind11_example, m) {
    m.doc() = "pybind11 example";

    py::enum_<Sentiment>(m, "Sentiment")
        .value("Angry", Angry)
        .value("Happy", Happy)
        .value("Confused", Confused)
        .export_values();

    m.def("mood", &mood, "Demonstrate using an enum");
}