#include
class Foo{ public: void bar(){ std::cout << "Hello" << std::endl; } };
extern "C" { Foo* Foo_new(){ return new Foo(); } void Foo_bar(Foo* foo){ foo->bar(); } }
g++ -c -fPIC foo.cpp -o foo.o g++ -shared -o libfoo.so foo.o
from ctypes import cdll lib = cdll.LoadLibrary('./libfoo.so')
class Foo(object): def init(self): self.obj = lib.Foo_new()
def bar(self):
lib.Foo_bar(self.obj)
f = Foo() f.bar() #and you will see "Hello" on the screen
The Python standard library includes ctypes, while swig and boost are not part of it. Unlike swig and boost, which depend on extension modules and are thus linked to specific Python minor versions, independent shared objects are not constrained by this limitation. Creating wrappers for swig or boost can be a challenging task, while ctypes does not impose any build requirements.