【问题标题】:Boost Python Hello World example not working in PythonBoost Python Hello World 示例在 Python 中不起作用
【发布时间】:2012-06-17 16:13:55
【问题描述】:

我在 Python 中使用来自 Visual C++(由 boost 包装)的 c++ 代码时遇到了很多麻烦。

好的,我使用的工具是:Visual Studio 2010、BoostPro 1_47、Windows 7 和 Python 2.7(32 位)。

我有以下代码可以在 Visual Studio 2010 中很好地编译:

#define BOOST_PYTHON_STATIC_LIB
#include <boost/python.hpp>
using namespace boost::python;

struct World
{
    void set(std::string msg) { this->msg = msg; }
    std::string greet() { return msg; }
    std::string msg;
};


BOOST_PYTHON_MODULE(hello)
{
    class_<World>("World")
            .def("greet", &World::greet)
            .def("set", &World::set);
}

格式为:Win32 Console Application >>>Empty Project / DLL.

在“项目属性”中:

VC++ DIRECTORIES: 
  I added:  
  >>> INCLUDE DIRECTORIES:  C:\Program Files\boost\boost_1_47;C:\Python27\include        .  
  >>> LIBRARY DIRECTORIES:  C:\Program Files\boost\boost_1_47\lib;C:\Python27\libs

所有这些都使 c++ 文件构建,但我无法从 Python 访问它。

这是我尝试使用该模块时 Python 所说的:

">>> import hello
 Traceback (most recent call last):
   File "<pyshell#0>", line 1, in <module>
     import hello
 ImportError: No module named hello

所以我想我的问题是......我怎样才能让 Python 找到它???

当 c++ 代码编译时,它会创建一个 DLL 文件。我必须更改文件的位置吗?如果有,应该放在哪里?

非常感谢您的帮助

【问题讨论】:

    标签: python c++ boost boost-python


    【解决方案1】:

    AFAIK 您必须将 DLL 的扩展名更改为 .pyd 否则 Python 将无法加载它。我认为您可以设置一个构建选项以在 VS 中自动设置扩展,但我不确定。

    另外,请确保创建的扩展位于 PYTHONPATH 路径上的某个位置,python 将查找要加载的模块。

    【讨论】:

    • 谢谢康斯坦丁! :D 经过几个小时和几个小时的尝试让 boost.python 完成它的工作,我终于让它工作了。
    • 你能提供一个成功的秘诀吗?
    • 我还必须将包含 Boost Python *.lib 和 *.dll 文件的目录添加到 PATH
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    相关资源
    最近更新 更多