user1449530 user1449530 - 1 month ago 15
C++ Question

Boost Python Hello World example not working in Python

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:

#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;

.def("greet", &World::greet)
.def("set", &World::set);

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

In "Project Properties":

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


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.