How to use a library made in C with python

Good evening! Sometimes a programming language like python (although powerful and versatile) may need more power or access to system libraries. To make use of a dynamic library type .DLL (windows) or .SO (linux) you can do it in the following way:

In this case we are going to create a test library in C for linux (the same C and python code can be used in Windows).

  • First step, we create the library with the following C language code:
user@host:~$ cat testintegration.c
#include <stdio.h>
#include <stdlib.h>

#ifdef _WIN32
#   define DLL_EXPORT __declspec(dllexport)
#else
#    define DLL_EXPORT
#endif

DLL_EXPORT int sum(int a, int b) {
   int res = 0;
   res = a + b;
   printf("ResC: %d\n",res) ;
   return res;
}

  • To compile it we use the following command (replace library with the desired name):
user@host:~$ gcc -Wall -Wextra -O -ansi -pedantic -fPIC -shared LIBRERIA.c -o /tmp/LIBRERIA.so
  • To use it in this language it is only necessary to call it by importing the cdll class of the ctypes module, after using the LoadLibrary method of the cdll class, we will be able to call the methods of the imported library:
user@host:~$ python
Python 2.7.9 (default, Jun 29 2016, 13:08:31) 
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import cdll;
>>> mydll = cdll.LoadLibrary('/tmp/LIBRERIA.so')
>>> mydll.sum(2,'a')
ResC: 1456018974
1456018974

More information at http://wolfprojects.altervista.org/articles/dll-in-c-for-python/

Leave a Reply