请参阅下面的c++代码,我正在尝试为
创建python绑定struct Config {
int a;
int b;
};
void myfunction(const Config &config);
这是我到目前为止写的
PYBIND11_MODULE(example, m) {
py::class_<Config>(m, "Config")
.def_readwrite("a", &Config::a)
.def_readwrite("b", &Config::b);
m.def("myfunction", &myfunction);
}
这可以编译,但是当我试图在python中调用python绑定时,
import example
config = example.Config;
config.a = 1;
config.b = 2;
example.myfunction(config)
我得到了下面的错误
TypeError: myfunction(): incompatible function arguments. The following argument types are supported:
1. (arg0: example.Config) -> None
Invoked with: <class 'example.Config'>
有人能让我知道什么是正确的方式来创建python绑定的函数,在一个结构体作为参数?
正如@eyllanesc所暗示的,这个问题将通过添加一个默认构造函数来解决:
PYBIND11_MODULE(example, m) {
py::class_<Config>(m, "Config")
.def(py::init<>())
.def_readwrite("a", &Config::a)
.def_readwrite("b", &Config::b);
m.def("myfunction", &myfunction);
}
import example
config = example.Config();
config.a = 1;
config.b = 2;
example.myfunction(config)