Log in


A tiny intro to Python ctypes

If you've ever been interested in interfacing with shared libraries and DLL using Python, then there are basically three ways you can achieve it. One is to use Python/C API, second is to use SWIG and the third which I will demonstrate is to use ctypes. ctypes is a great companion to keep around as it allows one to call functions and extract data as C types from a shared library without leaving the pleasant world of Python. Without further ado, let me roll some code.

#include < stdio.h >
#include < stdlib.h >
#include < string.h >

char* getenv2(char * environment)

return getenv(environment);

int _init()
printf("%s\n","Loaded ctype shared library");
return 0;

from ctypes import *
from ctypes.util import find_library
import sys

ctype_sl = cdll.LoadLibrary('./libctypedemo.so.1') # load library

getenv_ = ctype_sl.getenv2(sys.argv[1]) # get 1st arg
ret = c_char_p(getenv_) # cast to char*
if ret:
print "\{0}={1}".format(sys.argv[1],ret.value)

gcc -Wall -fPIC -c ctypedemo.c
gcc -shared -nostartfiles -Wl,-soname,libctypedemo.so.1 -o libctypedemo.so.1 -lc ctypedemo.o
export LD_PRELOAD=./libctypedemo.so.1


$ python ctypedemo.py PATH
Loaded ctype shared library

value for PATH=/usr/local/bin:/usr/local/sbin/:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/sbin:/bin:/usr/games

Hope you enjoyed the tiny intro. Feedbacks are welcome (constructive or destructive otherwise).