Summary - ctypes and CFFI
- Python course
- Expert
- Lesson 24/47
- 5 min
Combine CDLL, types and Structure to write a native wrapper.
Recap: ctypes and cffi
In this group you learned to call native C code from Python. You loaded libraries with CDLL and used C types with c_int and c_char_p.
You declared signatures with argtypes and restype. You saw the C-syntax alternative cffi. You modeled C structs with Structure. Now you will combine these into a native wrapper: a Point struct and an abs call together.
Practice Write a native wrapper
Import the module with import ctypes. Write a Point(ctypes.Structure) class; define _fields_ = [('x', ctypes.c_int), ('y', ctypes.c_int)]. Load the library with libc = ctypes.CDLL(None). Create an instance with Point(-3, 4). Print the result of libc.abs(p.x).
Starter code
# define Point and load libc
# call abs and printSample solution
import ctypes
class Point(ctypes.Structure):
_fields_ = [("x", ctypes.c_int), ("y", ctypes.c_int)]
libc = ctypes.CDLL(None)
p = Point(-3, 4)
print(libc.abs(p.x))Expected output
3
What you learned
In this group you learned to bridge Python and native C code. You loaded libraries with CDLL and used C types and signature declarations.
You saw the C-syntax alternative cffi. You modeled C structs with Structure. In the summary you combined a struct and a function call. This knowledge is important for systems programming and performance-critical applications.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match all ctypes concepts
| Term | Meaning |
|---|---|
CDLL |
Loads a library |
c_int |
C int type |
argtypes |
Argument types |
Structure |
C struct |
2 Which tool for which job?
- CDLL to define a struct
- argtypes to declare a signature Correct answer
- Structure to load a library
- cffi to make a web page
Explanation: answer: argtypes to declare a signature. CDLL loads a library, Structure defines a struct.
3 Final blank
libc = ctypes.____(None)
libc = ctypes.CDLL(None)
Explanation: CDLL(None) loads the default C library.