pybind11 中的命名默认参数

Named Default Arguments in pybind11

我正在使用 pybind11 将 C++ class 方法包装在转换 lambda "shim" 中(由于某些原因我必须这样做)。该方法的参数之一在 C++ 中是默认的。

class A
{
   void meow(Eigen::Matrix4f optMat = Eigen::Matrix4f::Identity());
};

在我的 pybind 代码中,我想保留这个可选参数:

py::class_<A>(m, "A")
       .def(py::init<>())
       .def("meow",
            [](A& self, Eigen::Matrix4f optMat = Eigen::Matrix4f::Identity()) 
            {
               return self.meow( optMat ); 
            });

如何在生成的 Python 代码中使 optMat 成为可选的命名参数?

只需在 lambda 之后添加它们:

py::class_<A>(m, "A")
    .def(py::init<>())
    .def("meow",
         [](A& self, Eigen::Matrix4f optMat) {
             return self.meow(optMat); 
         },
         py::arg("optMat") = Eigen::Matrix4f::Identity());