拆分pybind11模块和自动类型转换问题 我有一组模块,我用C++编写,并使用pybDun11导出到Python。所有这些模块都应该能够独立使用,但它们使用在实用程序库中定义的一组通用自定义类型 #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <string> #include "Color.hpp" std::vector<Color> buncha_colors(int n, std::string &color) { std::vector<Color> out; for (;n-- > 0;) { out.push_back(Color(color)); } return out; } PYBIND11_MODULE(pb11_example_module, m) { m.def("buncha_colors", &buncha_colors); }

拆分pybind11模块和自动类型转换问题 我有一组模块,我用C++编写,并使用pybDun11导出到Python。所有这些模块都应该能够独立使用,但它们使用在实用程序库中定义的一组通用自定义类型 #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <string> #include "Color.hpp" std::vector<Color> buncha_colors(int n, std::string &color) { std::vector<Color> out; for (;n-- > 0;) { out.push_back(Color(color)); } return out; } PYBIND11_MODULE(pb11_example_module, m) { m.def("buncha_colors", &buncha_colors); },python,c++,pybind11,Python,C++,Pybind11,在每个模块中都有如下代码。Color.hpp标题定义了实用程序库中使用的类型 #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <string> #include "Color.hpp" std::vector<Color> buncha_colors(int n, std::string &color) { std::vector<Color

在每个模块中都有如下代码。
Color.hpp
标题定义了实用程序库中使用的类型

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <string>
#include "Color.hpp"

std::vector<Color> buncha_colors(int n, std::string &color) {
    std::vector<Color> out;
    for (;n-- > 0;) {
        out.push_back(Color(color));
    }
    return out;
}

PYBIND11_MODULE(pb11_example_module, m) {
    m.def("buncha_colors", &buncha_colors);
}

理想情况下,我希望将所有这些自定义实用程序类型和相关函数与使用它们的所有模块分开保存在一个单独的模块中。但是我需要在使用它的每个模块中定义类型转换,或者引用它。我该怎么办?我不想要
pb11\u示例\u module.Color
utils.Color
等等。我不知道它们是否兼容,这似乎是一种错误的方式。

这开始只是一个编辑,但后来证明是我的答案

这很有趣。使用第一个示例,其中pybind模块中未导出
Color

$ python
>>> import pb11_example_module
>>> pb11_example_module.buncha_colors(10, "red")[0].name()
TypeError: Unable to convert function return value to a Python type! The signature was
    (arg0: int, arg1: str) -> List[Color]
>>> import utils  # defines Color
>>> pb11_example_module.buncha_colors(10, "red")[0].name()
'red'
在导入示例模块之前导入实用程序库也有效。将类名
“Color”
更改为其他名称也不会中断使用,因此它必须使用类型签名从其他模块获取类型转换


只要在使用之前定义C++类型的类型转换,自动类型转换就可以工作。pybind用于Python的类型转换实用程序是全局的,并在运行时查找。你可以阅读所有关于它的内容。上述在使用之前的任何时候为自定义类型加载类型转换的解决方案是受支持的惯用解决方案。

接下来,我认为更具idomatic的解决方案(在绑定中)是确保使用
py::module::import(“my_package.my_depdency”)
导入模块。最终,b/c您正在使用您提到的全局注册表进行绑定,导入模块有一个副作用——通过RTTI注册类型。如果在绑定中导入模块依赖项,那么就可以开始了。下面是一个PR+测试的例子,如果忘记了这一点(对于我们的代码),它会很快失败:@EricCousineau很棒的提示!