c++ - 使用 Visual Studio 2008 构建 boost python 示例

标签 c++ python boost-python

我正在使用 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/

相关文章:

c++ - 动态内存分配

c++ - 在函数 `uv__signal_global_init' : . .. 对 `pthread_atfork' 的 undefined reference

python - 扭曲的网络获取主机:port tuple in async response

Python复制具有相同ID值的行

c++ - 将派生类型的对象从 python 传递到期望 shared_ptr 为基类型的 C++ 函数时,Boost Python 运行时错误

c++ - 重载可变参数模板的固定参数

c++ - 适用于 C++ 的良好 Windows 注册表包装器

python - 将 pandas 数据框分层拆分为训练、验证和测试集

python - 无法在 Windows 7 中安装图形工具

c++ - 在boost python中用map_indexing_suite包装一个string/shared_ptr unordered_map