Python – Calling C/C++ from Python?


What would be the quickest way to construct a Python binding to a C or C++ library?

(I am using Windows if this matters.)

Best Solution

ctypes module is part of the standard library, and therefore is more stable and widely available than swig, which always tended to give me problems.

With ctypes, you need to satisfy any compile time dependency on python, and your binding will work on any python that has ctypes, not just the one it was compiled against.

Suppose you have a simple C++ example class you want to talk to in a file called foo.cpp:

#include <iostream>

class Foo{
        void bar(){
            std::cout << "Hello" << std::endl;

Since ctypes can only talk to C functions, you need to provide those declaring them as extern "C"

extern "C" {
    Foo* Foo_new(){ return new Foo(); }
    void Foo_bar(Foo* foo){ foo->bar(); }

Next you have to compile this to a shared library

g++ -c -fPIC foo.cpp -o foo.o
g++ -shared -Wl,-soname, -o  foo.o

And finally you have to write your python wrapper (e.g. in

from ctypes import cdll
lib = cdll.LoadLibrary('./')

class Foo(object):
    def __init__(self):
        self.obj = lib.Foo_new()

    def bar(self):

Once you have that you can call it like

f = Foo() #and you will see "Hello" on the screen