使用 Pybind11 将 C++ 扩展到 Python

Extending C++ to Python using Pybind11

我有一些用 C++ 编写的代码,我试图在 python 中使用这些代码,而无需再次重写 python 中的完整代码,我正在使用 Pybind11 构建一个 python模块。 我正在尝试按照此处的本教程 https://pybind11.readthedocs.io/en/stable/basics.html

在 Microsoft Visual Studio 2015 中实现此功能

我在 visual studio 中做了以下事情。 1) 从 https://codeload.github.com/pybind/pybind11/zip/master

下载 Pybind11

2) 解压缩文件

3) 在 visual studio 中,a 启动了一个新的空 C++ 项目。

4) 在 VC++ 目录中添加了我的 python 解释器包含文件夹 ( C:/python27/include) 和 Pybind11( C:/Pybind11/include) > 包含目录

5) 在 Linker>input>Additional dependencies

中添加了附加依赖项 (C:\Python27\libs\python27.lib)

6) 要使用 Python 中的输出文件,我需要一个 .pyd 文件,所以我在此处修改了 Configuration Properties>General>Target extension : .pyd

7) 将项目默认值 > 配置类型更改为动态库 (.dll)

所以我能够构建我的项目并生成 .pyd 文件但是当导入这个模块时我收到以下错误: ImportError: 动态模块没有定义 init 函数 (initProject11)

我搜索了这个错误并得到了这个 link http://pybind11.readthedocs.io/en/stable/faq.html 但我找不到我的解决方案。

所以我正在寻找上述问题的解决方案。非常感谢。

这是我的 CPP 文件代码

#include <pybind11/pybind11.h>

int add(int i, int j) {
return i + j;
}

namespace py = pybind11;

PYBIND11_PLUGIN(example) {
    py::module m("example", "pybind11 example plugin");

    m.def("add", &add, "A function which adds two numbers");

    return m.ptr();
}

在python中,.pyd文件的名称必须与里面的模块相同。来自文档 (https://docs.python.org/2/faq/windows.html):

If you have a DLL named foo.pyd, then it must have a function initfoo(). You can then write Python “import foo”, and Python will search for foo.pyd (as well as foo.py, foo.pyc) and if it finds it, will attempt to call initfoo() to initialize it.

在您的代码中,您创建了一个名为 example 的 python 模块,因此输出文件必须是 example.pyd.

编辑:

pybind11 常见问题解答提到不兼容的 python 版本作为另一个可能的错误源 (https://pybind11.readthedocs.io/en/stable/faq.html):

ImportError: dynamic module does not define init function

  1. Make sure that the name specified in pybind::module and PYBIND11_PLUGIN is consistent and identical to the filename of the extension library. The latter should not contain any extra prefixes (e.g. test.so instead of libtest.so).

  2. If the above did not fix your issue, then you are likely using an incompatible version of Python (for instance, the extension library was compiled against Python 2, while the interpreter is running on top of some version of Python 3, or vice versa)