The PyBind11 documentation talks about using enum
here.
The example shown assumes that the enum is embedded within a class, like so:
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();
My situation is different. I have a global enum
the value of which is used to alter the behaviour of several functions.
enum ModeType {
COMPLETE,
PARTIAL,
SPECIAL
};
std::vector<int> Munger(
std::vector<int> &data,
ModeType mode
){
//...
}
I have tried to register it like so:
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");
}
Compilation is successful and the module loads in Python, but I do not see ModeType in the module's names.
What can I do?
the sample below works for me. Like in my comment I used an "unscoped enum" (github.com/pybind/pybind11/blob/master/tests/test_enum.cpp).
I can use it like this
import pybind11_example as ep
ep.mood(ep.Happy)
code:
#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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With