CodeBlanks Logo Icon CodeBlanks

argtypes and restype

Learn to specify signatures with argtypes and restype.

What are argtypes and restype?

To call a C function correctly you must declare its signature. argtypes lists the argument types and restype sets the return type.

For example libc.strlen.argtypes = [c_char_p] specifies a single char* argument. libc.strlen.restype = c_size_t says the return is size_t. Without these Python defaults to c_int and a size_t return may be truncated. Type declaration is mandatory for both safety and portability.

Type safety

When argtypes and restype are set Python converts arguments automatically and warns on wrong types. This prevents silent errors.

For example if argtypes = [c_char_p] is set and you write libc.strlen(42) Python raises a TypeError. Without type declaration this would silently misbehave. That is why production code always declares signatures. Also without restype large return values can be truncated.

Practice Write a signature for strlen

Import the module with import ctypes. Load libc with ctypes.CDLL(None). Set libc.strlen.argtypes = [ctypes.c_char_p] and libc.strlen.restype = ctypes.c_size_t. Print the result of libc.strlen(b"merhaba").

Starter code

main.py
# pick a function from the library
# set its signature and call it

Sample solution

main.py
import ctypes

libc = ctypes.CDLL(None)
libc.strlen.argtypes = [ctypes.c_char_p]
libc.strlen.restype = ctypes.c_size_t
print(libc.strlen(b"merhaba"))

Expected output

7

Questions and answers

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

1 What does restype specify?

main.py
libc.strlen.restype = ctypes.c_size_t
  • The return type Correct answer
  • The library name
  • The argument types
  • The function name

Explanation: restype sets the C type of the function's return value.

2 Match signature concepts

Term Meaning
argtypes Argument types
restype Return type
c_char_p char* argument
c_size_t size_t return

3 Complete the argtypes assignment

Question
libc.strlen.____ = [ctypes.c_char_p]
Answer
libc.strlen.argtypes = [ctypes.c_char_p]

Explanation: argtypes takes a list of argument types.

All lessons in Expert