David Menard
David Menard

Reputation: 2321

Importing python boost module

I built a DLL in VS2010 with boost::python to export some function to a python module:

myDLL.cpp:

std::string greet() { return "hello, world"; }
int square(int number) { return number * number; }

BOOST_PYTHON_MODULE(getting_started1)
{
    // Add regular functions to the module.
    def("greet", greet);
    def("square", square);
}

Up to here, everything compiles just fine. I then get the myDLL.dll and myDLL.lib file in c:\myDLL\Debug.

According to boost doc (http://wiki.python.org/moin/boost.python/SimpleExample), I need to add this to PYTHONPATH, so I added c:\myDLL\Debug to it: PYTHONPATH: C:\Python27;c:\myDLL\Debug;

then, from my .py file, I try to import it:

import getting_started1
print getting_started1.greet()
number = 11
print number, '*', number, '=', getting_started1.square(number)

I have also tried from myDLL import getting_started1, and from getting_started1 import *, and all possible combinations of sorts.

Can anyone tell me how am I supposed to call my module? Thanks

EDIT: According to cgohlke, there should be a getting_started1.pyd somewhere in my PYTHONPATH when I compile in VS? This file is inexistant... Do I have to set somethign different in VS2010? I have a default win32 DLL project. But the boost doc says " If we build this shared library and put it on our PYTHONPATH", isn't a shared library on windows a DLL? ergo, the DLL should be in the PYTHONPATH?

Upvotes: 0

Views: 1770

Answers (2)

Yalon Lotan
Yalon Lotan

Reputation: 11

  1. I managed to get it working only in Release configuration and not in Debug.
  2. From the project properties, on the General tab, modify Target Extension to .pyd
  3. The project should be indeed a dll, as you did
  4. In the Python script you need to specify the location of the dll as in this example: import sys sys.path.append("d:\\TheProjectl\\bin\\Release") import getting_started #Dll name without the extension

Upvotes: 0

cgohlke
cgohlke

Reputation: 9417

The standard, portable way to build Python extensions is via distutils. However, Visual Studio 2010 is not a supported compiler for Python 2.7. The following setup.py works for me with Visual Studio 2008 and boost_1_48_0. The build command is python setup.py build_ext --inplace.

# setup.py
from distutils.core import setup
from distutils.extension import Extension
setup(name="getting_started1",
    ext_modules=[
        Extension("getting_started1", ["getting_started1.cpp"],
        include_dirs=['boost_1_48_0'],
        libraries = ['boost_python-vc90-mt-1_48'],
        extra_compile_args=['/EHsc', '/FD', '/DBOOST_ALL_DYN_LINK=1']
        )
    ])

For your Visual Studio 2010 project, try to change the linker output file to getting_started1.pyd instead of myDLL.dll.

Upvotes: 2

Related Questions