views:

384

answers:

3

I'm using Boost Python library to create python extensions to my C++ code. I'd like to be able to invoke from python the 'greet' function from the C++ code shown below:

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

And the python code :

import hello_ext
print hello_ext.greet() 

I've managed to do this using the bjam (hello_ext.pyd is generated and it works nice), but now I'd like to build it using Visual Studio 2008. A hello.dll gets built (but neither hello_ext.dll nor any .pyd). After invoking my python code I get an error:

ImportError: No module named hello_ext.

After renaming the hello.dll to hello.pyd or hello_ext.pyd, I get another ImportError: Dll load failed

How can I build the correct .pyd file using VS 2008?

A: 

Please make sure you have flag -lpython26 (if you are using python2.6) and filename should be hello_ext.pyd in your case.

S.Mark
+2  A: 

Firstly, make sure you only try to import the release version from Python; importing the debug version will fail because the runtime library versions don't match. I also change my project properties so that the release version outputs a .pyd file:

Properties >> Linker >> Output:

$(OutDir)\$(ProjectName).pyd

(I also create a post-build action to run unit tests from python)

Next, make sure you define the following in your stdafx.h file:

#define BOOST_PYTHON_STATIC_LIB

Lastly, if you have more than one python version installed, make sure that you're importing the right version of python.h (in Tools >> Options >> Projects and Solutions >> VC++ Directories >> Include Files).

Ryan Ginstrom
A: 

The error ImportError: Dll load failed usually means that your .pyd module depends on other DLLs that couldn't be found - often msvc*.dll. You may want to try opening the .pyd file in Notepad and searching for ".dll". Then check if all of the DLL dependencies exist in your directory or PATH.

AndiDog