A quick-start memento for cytpes. Used on vanila Debian 6.0.7 (squeeze), python 2.7.3

(instruction on how to install second python on Debian: https://gist.github.com/ftao/1069219)

 

C

hello.c

#include<stdio.h>
hello() {
    printf("Hello World\n");
}

compile:

$ gcc -c hello.c -o hello.o

link in shared library:

g++ -shared -Wl,-soname,hello.so -o hello.so hello.o

helloWrapper.py:

from ctypes import cdll
lib = cdll.LoadLibrary('./hello.so')
def hello():
    lib.hello()

run python:

$ python
>>> import helloWrapper
>>> helloWrapper.hello()
Hello World




C++

Taken from: http://stackoverflow.com/a/145649/236195

 foo.cpp

#include <iostream>

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(); }
}

compile into a shared library:

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

fooWrapper.py:

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)

 run python:

$ python
>>> import fooWrapper
>>> f = fooWrapper.Foo()
>>> f.bar()
Hello



Great success!