Lab 05: C Extension via ctypes
Overview
Step 1: Loading C Libraries
import ctypes
import sys
# Load the C standard library
if sys.platform == 'linux':
libc = ctypes.CDLL("libc.so.6")
elif sys.platform == 'darwin':
libc = ctypes.CDLL("libc.dylib")
else:
libc = ctypes.cdll.msvcrt # Windows
# Call simple functions
libc.puts(b"Hello from libc.puts!")
# strlen
libc.strlen.restype = ctypes.c_size_t
libc.strlen.argtypes = [ctypes.c_char_p]
length = libc.strlen(b"hello world")
print(f"strlen('hello world') = {length}")
# abs
libc.abs.restype = ctypes.c_int
libc.abs.argtypes = [ctypes.c_int]
print(f"abs(-42) = {libc.abs(-42)}")Step 2: Basic Types
Step 3: Calling qsort with Callback
qsort with CallbackStep 4: ctypes.Structure — Mapping C Structs
ctypes.Structure — Mapping C StructsStep 5: ctypes.Union
ctypes.UnionStep 6: ctypes.cast and Pointer Arithmetic
ctypes.cast and Pointer ArithmeticStep 7: malloc / free via ctypes
malloc / free via ctypesStep 8: Capstone — Shared Library Wrapper
Summary
Concept
API
Use Case
Last updated
