ctypes types
- Python course
- Expert
- Lesson 20/47
- 5 min
Learn C types with c_int, c_char_p.
c_int and c_char_p
ctypes provides classes that represent C types in Python. c_int stands for C int, c_char_p for a C char* pointer.
After creating a C type you access the Python value through .value. c_int(42).value gives 42. c_char_p(b"kutu").value gives the byte string b"kutu"; you convert it to text with .decode(). These types are needed to match function arguments and return values correctly.
Other C types
ctypes provides many C types: c_double (double), c_long (long), c_size_t (size_t), c_void_p (void*).
Each type's .value attribute works for both reading and writing. a = c_int(5); a.value = 10 changes the value. The types are used as class names when defining argtypes and restype. Choosing the right type prevents data loss and crashes.
Practice Store values with C types
Import the module with import ctypes. Create a C int with ctypes.c_int(42). Create a C string pointer with ctypes.c_char_p(b"kutu"). Print the .value of both; decode the second to text with .decode().
Starter code
# create C types
# print the valuesSample solution
import ctypes
a = ctypes.c_int(42)
b = ctypes.c_char_p(b"kutu")
print(a.value)
print(b.value.decode())Expected output
42 kutu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the c_int definition
a = ctypes.____(42)
a = ctypes.c_int(42)
Explanation: c_int(42) creates a C int object.
2 Match type concepts
| Term | Meaning |
|---|---|
c_int |
C int |
c_char_p |
char* pointer |
.value |
Python value |
.decode() |
Bytes to text |
3 What does c_char_p(b'x').value return?
import ctypes
s = ctypes.c_char_p(b'kutu')
print(s.value)- An error
- A number
- A text string
- A bytes string Correct answer
Explanation: answer: a bytes string. c_char_p.value returns bytes; decode is needed for text.