Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows basic usage of the ctypes module to call C code from Python code.

Python, 21 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# libc_time.py
# Example of calling C library functions from Python
# using the Python ctypes module.
# Author: Vasudev Ram
# Copyright 2016 Vasudev Ram - https://vasudevram.github.io

from __future__ import print_function
from ctypes import cdll
import time

libc = cdll.msvcrt

def test_libc_time(n_secs):
    t1 = libc.time(None)
    time.sleep(n_secs)
    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):
    test_libc_time(i)

The recipe uses the ctypes module to access the time() function in the C runtime library, and make calls to it. The time.sleep() function of Python is used to verify that the calls to time() return the right values.

More details and sample output at this URL:

http://jugad2.blogspot.in/2016/05/calling-c-from-python-with-ctypes.html