Suppose we have the following C++ API which we want to expose in Python:
#include <string>
namespace hello {
class world
{
public:
world(int);
~world();
std::string get() const { return "hi, world"; }
...
};
std::size_t length(const world& x) { return std::strlen(x.get()); }
}
Here is the C++ code for a python module called hello
which exposes the API using py_cpp:
#include// Python requires an exported function called init<module-name> in every // extension module. This is where we build the module contents. extern "C" #ifdef _WIN32 __declspec(dllexport) #endif void inithello() { try { // create an object representing this extension module boost::python::module_builder hello("hello"); // Create the Python type object for our extension class boost::python::class_builder<hello::world> world_class(hello, "world"); // Add the __init__ function world_class.def(boost::python::constructor<int>()); // Add a regular member function world_class.def(&hello::world::get, "get"); // Add a regular function to the module hello.def(hello::length, "length"); } catch(...) { boost::python::handle_exception(); // Deal with the exception for Python } } // Win32 DLL boilerplate #if defined(_WIN32) #include <windows.h> extern "C" BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID) { return 1; } #endif // _WIN32
That's it! If we build this shared library and put it on our
PYTHONPATH we can now access our C++ class and function from
Python.
>>> import hello >>> hi_world = hello.world(3) >>> hi_world.get() 'hi, world' >>> hello.length(hi_world) 9
We can even make a subclass of hello.world:
>>> class my_subclass(hello.world): ... def get(self): ... return 'hello, world' ... >>> y = my_subclass(4) >>> y.get() 'hello, world'
Pretty cool! You can't do that with an ordinary Python extension type!
>>> hello.length(y) 9
Of course, you may now have a slightly empty feeling in the pit of
your little pythonic stomach. Perhaps you feel your subclass deserves
to have a length() of 12? If so, read on...
Previous: Comparisons with other systems Next: Overridable virtual functions Up: Top
© Copyright David Abrahams 2000. Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.
Updated: Nov 26, 2000