Sunday, May 8, 2016

Calling C from Python with ctypes

By Vasudev Ram

Python => C

ctypes is a module in the Python standard library. It is "a foreign function library for Python". Such libraries help with calling code written in language B, from language A. In the case of ctypes it helps with calling C code from Python code.

[ Note: There are various other methods of linking between Python code and code written in other languages, such as writing Python extensions using the Python C API, SWIG, cffi, etc. I am only looking at ctypes in this post. It is one of the simpler methods. May look at others later. ]

Here is a small example of using ctypes, to call the time() function in the C runtime library on Windows:

# Example of calling C library functions from Python
# using the Python ctypes module.
# Author: Vasudev Ram
# Copyright 2016 Vasudev Ram

from __future__ import print_function
from ctypes import cdll
import time

libc = cdll.msvcrt

def test_libc_time(n_secs):
    t1 = libc.time(None)
    t2 = libc.time(None)
    print("n_secs = {}, int(t2 - t1) = {}".format(n_secs, int(t2 - t1)))
print("Calling the C standard library's time() function via ctypes:")
for i in range(1, 6):
And here is the output:
$ python
Calling the C standard library's time() function via ctypes:
n_secs = 1, int(t2 - t1) = 1
n_secs = 2, int(t2 - t1) = 2
n_secs = 3, int(t2 - t1) = 3
n_secs = 4, int(t2 - t1) = 4
n_secs = 5, int(t2 - t1) = 5
Note: libc.time() is the Python interface [1] to the C time() function, and time.sleep() is the sleep function in the time module of the Python standard library.

[1] We obtain that interface using ctypes; see the program above.

I use a call to time.sleep() sandwiched between two calls to libc.time(), to verify that the calls to libc.time() are returning the correct result; as you can see from the output, they are doing so.

- Vasudev Ram - Online Python training and consulting

Signup to hear about my new courses and products.

My Python posts     Subscribe to my blog by email

My ActiveState recipes

No comments: