gpt4 book ai didi

c++11 - PyBind11 全局级枚举

转载 作者:行者123 更新时间:2023-12-01 09:24:18 25 4
gpt4 key购买 nike

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。

我能做些什么?

最佳答案

下面的示例对我有用。就像在我的评论中一样,我使用了“无范围枚举”(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");
}

关于c++11 - PyBind11 全局级枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47893832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com