Suppose we have the following C++ API which we want to expose in Python:
namespace hello {
class world
{
public:
world(int);
~world();
const char* get() const { return "hi, world"; }
...
};
void 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 <py_cpp/class_wrapper.h>
// 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
py::Module hello("hello");
// Create the Python type object for our extension class
py::ClassWrapper<hello::world> world_class(hello, "world");
// Add the __init__ function
world_class.def(py::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(...)
{
py::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: Oct 15, 2000