CodeBlanks Logo Icon CodeBlanks

ctypes.CDLL

Learn to load native libraries with ctypes.CDLL.

What is ctypes.CDLL?

The ctypes module lets Python call native C libraries. The CDLL class loads a shared library and exposes its functions.

CDLL(None) loads the default C library (libc on Linux). You can then call functions like libc.abs(-7) through the loaded object. The default return type is c_int. This is the most direct way to bridge Python and C, and is common in systems programming.

Calling a function

You access functions on a CDLL object with a dot: libc.abs(-7). Python converts arguments to C types automatically.

The default return type is c_int. If the function returns a different type (such as size_t) you must specify it with restype. Otherwise the return value may be truncated. The call is synchronous and fast as in C; but type mismatches can cause crashes.

Practice Call abs with CDLL

Import the module with import ctypes. Load the default C library with ctypes.CDLL(None). Assign the result of libc.abs(-7) to a variable and print it.

Starter code

main.py
# load libc
# call the abs function
# print the result

Sample solution

main.py
import ctypes

libc = ctypes.CDLL(None)
result = libc.abs(-7)
print(result)

Expected output

7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match CDLL concepts

Term Meaning
CDLL Loads a library
None Default libc
.abs(-7) Function call
c_int Default return

2 What does CDLL(None) load?

main.py
import ctypes
libc = ctypes.CDLL(None)
  • The default C library Correct answer
  • A Python standard module
  • It raises an error
  • An empty object

Explanation: CDLL(None) loads the default C library of the process.

3 Complete the CDLL call

Question
libc = ctypes.____(None)
Answer
libc = ctypes.CDLL(None)

Explanation: CDLL(None) loads the default C library.

All lessons in Expert