第一次运行pybind,结果总是报错
TypeError: useOp(): incompatible function arguments. The following argument types are supported:
1. (arg0: cost_model.OpInfo) -> None
Invoked with: <class 'cost_model.OpInfo'>
我的代码大概如下:
//C++
struct OpInfo {
std::string type;
...
};
void useOp(const OpInfo &op) {
std::cout << "op type is " << op.type << std::endl;
}
PYBIND11_MODULE(try_pybind, m) {
namespace py = pybind11;
py::class_<OpInfo>(m, "OpInfo")
.def(py::init<>())
.def_readwrite("type", &OpInfo::type)
;
m.def("useOp", &useOp);
}
//python
import try_pybind
op0 = try.OpInfo
op0.type = "whatever"
try.useOp(op0)
我一直以为这明明是正确的,或者错误在C++中,瞎试了半天,最后发现是因为op0 = try.OpInfo这句,应该是op0 = try.OpInfo(). 没想到python会把一个类也作为对象,且不报错。有没有括号决定是类还是对象。作此笔记,引以为戒。