python - 使用 Pybind11 将 C++ 扩展到 Python

标签 python c++ visual-studio-2015 pybind11

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

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

2) 解压文件

3) 在 vi​​sual studio 中启动一个新的空 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: 动态模块没有定义初始化函数 (initProject11)

我搜索了这个错误并得到了这个链接 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 FAQ 提到不兼容的 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)

关于python - 使用 Pybind11 将 C++ 扩展到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45054860/

相关文章:

python - 如何删除 EOFError : EOF when reading a line?

Python递归地__getattribute__

c++ - n叉树的最低共同祖先

c++ - 如何让 wstring_convert::to_bytes 抛出 range_error 异常?

visual-studio-2015 - 如何设置 IBM DB2 9.7 以使用 Entity Framework 6 和 Visual Studio 2015?

Python 货币代码放入列表中

python - 使用 python 和 numpy 的二维卷积

c++ - 有关条件 block 的问题与&&运算符有关

c++ - soci给出 fatal error :mysql.h:没有这样的文件或目录

unit-testing - MSTest.exe 通过 cmd 找不到测试用例,但在 VS2015 IDE 中工作正常