使用 pybind11 将 C++ 函数添加到现有 python 模块

Add c++ function to existing python module with pybind11

如何使用 pybind11 创建 python 个子模块?

我克隆了 python 示例 (https://github.com/pybind/python_example) 并对其进行了修改。下面是目录树。

*
|
+-- src
|   |
|   +-- example.cpp 
|
+-- setup.py
|
+-- python_example
     |
     +-- __init__.py
     |
     +-- cxx
         |
         +-- __init__.py

setup.py 有以下几行:

ext_modules = [
    Extension(
        'python_example.cxx',
        ['src/main.cpp'],
        include_dirs=[
            # Path to pybind11 headers
            get_pybind_include(),
            get_pybind_include(user=True),
            "include",  # the include folder
        ],
        language='c++'
    ),
]



setup(
    ...
    packages=setuptools.find_packages(),
    ...
)

以下内容无效,因为它不能使用带点的名称。

PYBIND11_PLUGIN(python_example.cxx) {
    ...
}

以下也不行。

PYBIND11_PLUGIN(python_example) {
    py::module m = py::module::import("python_example.cxx");

    m.def("add", &add, R"pbdoc(
        Add two numbers

        Some other explanation about the add function.
    )pbdoc");
}

这也不行:

py::module m2 = (py::module) py::module::import("python_example").attr("cxx");

m2.def("add", &add, R"pbdoc(...

如何进行这项工作?

cxx 是一个子包,您尝试构建一个同名的二进制模块。尝试以不同的方式命名二进制模块以避免名称冲突。

setup.py:

ext_modules = [
    Extension(
        'python_example.cxx.cxx_module',
...

main.cpp:

PYBIND11_PLUGIN(cxx_module) {
    ...
}