我正在使用 Boost Python 库为我的 C++ 代码创建 Python 扩展。我希望能够从 python 从如下所示的 C++ 代码中调用“问候”函数:
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
char const* greet()
{
return "hello, world";
}
BOOST_PYTHON_MODULE(hello_ext)
{
using namespace boost::python;
def("greet", greet);
}
和 python 代码:
import hello_ext
print hello_ext.greet()
我已经使用 bjam 成功地做到了这一点(生成了 hello_ext.pyd,它运行良好),但现在我想使用 Visual Studio 2008 构建它。一个 hello.dll 被构建(但 hello_ext.pyd 都没有构建)。 dll 或任何 .pyd)。调用我的 python 代码后出现错误:
导入错误:没有名为 hello_ext 的模块。
将 hello.dll 重命名为 hello.pyd 或 hello_ext.pyd 后,我得到另一个 ImportError: Dll load failed
如何使用 VS 2008 构建正确的 .pyd 文件?
最佳答案
首先,请确保您只尝试从 Python 导入发布版本;导入调试版本将失败,因为运行时库版本不匹配。我还更改了我的项目属性,以便发布版本输出一个 .pyd 文件:
属性>>链接器>>输出:
$(OutDir)\$(ProjectName).pyd
(我还创建了一个构建后操作来从 python 运行单元测试)
接下来,确保在 stdafx.h 文件中定义以下内容:
#define BOOST_PYTHON_STATIC_LIB
最后,如果您安装了多个 python 版本,请确保您正在导入正确版本的 python.h(在工具 >> 选项 >> 项目和解决方案 >> VC++ 目录 >> 包含文件中)。
关于c++ - 使用 Visual Studio 2008 构建 boost python 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2018908/