CodeBlanks Logo Icon CodeBlanks

ctypes

Write a native code call with ctypes.

The native code layer

In this lesson you will add calling abs from a C library with ctypes. ctypes.CDLL(None) loads the default C library.

The libc.abs(-7) call gives the absolute value of a negative number. The previous lessons' code is already in the starting code. You only add import ctypes, CDLL(None) and the abs call. This layer will be combined with parallel processing in the final lesson.

Practice Call abs with ctypes

The starting code already has Tool, Field, ModelMeta and square. Now import the module with import ctypes. Load the library with libc = ctypes.CDLL(None). Print the absolute value with print(libc.abs(-7)).

Starter code

main.py
# Build the Tool class with type()
Tool = type("Tool", (), {
    "name": "arac",
    "run": lambda self: f"{self.name} calisti",
})

# Add Field descriptor and ModelMeta
class Field:
    def __set_name__(self, owner, name):
        self.name = name
        if not hasattr(owner, "fields"):
            owner.fields = []
        owner.fields.append(name)

class ModelMeta(type):
    def __new__(mcs, name, bases, ns):
        return super().__new__(mcs, name, bases, ns)

class Model(metaclass=ModelMeta):
    ad = Field()

# Add parallel square computation
from multiprocessing import Pool

def square(x):
    return x * x

# Add native abs call
# load libc and call abs
# print the result

Sample solution

main.py
# Build the Tool class with type()
Tool = type("Tool", (), {
    "name": "arac",
    "run": lambda self: f"{self.name} calisti",
})

# Add Field descriptor and ModelMeta
class Field:
    def __set_name__(self, owner, name):
        self.name = name
        if not hasattr(owner, "fields"):
            owner.fields = []
        owner.fields.append(name)

class ModelMeta(type):
    def __new__(mcs, name, bases, ns):
        return super().__new__(mcs, name, bases, ns)

class Model(metaclass=ModelMeta):
    ad = Field()

# Add parallel square computation
from multiprocessing import Pool

def square(x):
    return x * x

# Add native abs call
import ctypes

libc = ctypes.CDLL(None)

print(libc.abs(-7))

Expected output

7

Next step: integration

The ctypes layer is ready. In the final lesson you will combine all layers: an abs_val function that calls libc.abs and runs in parallel with Pool.map.

This combines metaprogramming, multiprocessing and ctypes in one application. So far four layers are ready: Tool, Field/ModelMeta, Pool and ctypes.

Questions and answers

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

1 What does CDLL load?

main.py
import ctypes
libc = ctypes.CDLL(None)
  • A Python module
  • A web page
  • A shared C library Correct answer
  • An array

Explanation: CDLL loads a shared C library.

2 Match ctypes concepts

Term Meaning
ctypes C interface
CDLL Loads a library
libc Library object
.abs Function call

3 Complete the CDLL call

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

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

All lessons in Expert