Python Programming/Extending with C++
From Wikibooks, the open-content textbooks collection
| Previous: Extending with C | Index | Next: Extending with Pyrex |
Boost.Python is the de facto standard for writing C++ extension modules. Boost.Python comes bundled with the Boost C++ Libraries.
[edit] The C++ source code (hellomodule.cpp)
#include <iostream> using namespace std; void say_hello(const char* name) { cout << "Hello " << name << "!\n"; } #include <boost/python/module.hpp> #include <boost/python/def.hpp> using namespace boost::python; BOOST_PYTHON_MODULE(hello) { def("say_hello", say_hello); }
[edit] setup.py
#!/usr/bin/env python from distutils.core import setup from distutils.extension import Extension setup(name="blah", ext_modules=[ Extension("hello", ["hellomodule.cpp"], libraries = ["boost_python"]) ])
Now we can build our module with
python setup.py build
The module `hello.so` will end up in e.g `build/lib.linux-i686-2.4`.
[edit] Using the extension module
Change to the subdirectory where the file `hello.so` resides. In an interactive python session you can use the module as follows.
>>> import hello
>>> hello.say_hello("World")
Hello World!
| Previous: Extending with C | Index | Next: Extending with Pyrex |