How to include in Python a function made in C?

8

I want to use a function made in C .

Example:

I have a function

int swap(){ 
    printf("lista");
}

And I want to call it Python ...

    
asked by anonymous 23.10.2015 / 18:32

1 answer

8

The first thing you'll have to do is to generate a dynamic library with your C code. On Linux this means a ".so" library and on windows it would be a ".dll"

Assuming you are on Linux and the name of your C file is "hello.c", gcc can generate this dynamic library through next command :

gcc -shared -o libhello.so -fPIC hello.c

Now to call this Python library you can use the ctypes library, which is part of the standard Python library:

import ctypes

libhello = ctypes.cdll.LoadLibrary("./libhello.so")
libhello.swap()

For more advanced examples, where the function receives or returns parameters, you will need to convert the data from Python to C format. See the ctypes documentation for details.

    
23.10.2015 / 19:17