Boost Python Hello World example not working in Python

走远了吗. 提交于 2019-12-04 21:49:43

问题


I'm having a great deal of trouble using my c++ code from Visual C++ (wrapped by boost) in Python.

Alright, so the tools I'm using are: Visual Studio 2010, BoostPro 1_47, Windows 7, and Python 2.7 (32-bit).

I have the following code which compiles nicely in 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);
}

It's in the format: Win32 Console Application >>>Empty Project / DLL.

In "Project Properties":

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

All of this makes the c++ file build but then I can't access it from Python.

This is what Python says when I try to use the module:

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

So I guess my question is... How can I get Python to find it???

When the c++ code compiles it creates a DLL file. Do I have to change the location of the file? If so, where should I put it?

Your help would be greatly appreciated


回答1:


AFAIK you have to change the extension of the DLL to .pyd or otherwise Python will not be able to load it. I think you can set a build option to automatically set the extension in VS, but I don't know for sure.

Also, make sure that the created extension is somewhere on the PYTHONPATH, the path, python will look for modules to load.



来源:https://stackoverflow.com/questions/11036319/boost-python-hello-world-example-not-working-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!