ctypes – Python’s awesome low-level library

Last week I purchased the book Gray Hat Python, by Justin Seitz. Though, I’m somewhat skeptical that I’m going to be finishing reading the book anytime soon, I started reading it’s first chapter. It appears that the book is going to be mostly based on Python’s ctypes library. Which in short, this really cool library lets you create complex C datatypes and low-level memory manipulation in pure Python code. One thing that really impressed me about cytpes is its ability to call functions in dynamically linked libraries. For example, with ctypes, you’re able to call the printf function from both Linux’s and Windows C runtime libraries, which I think it’s really cool.

Linux


from ctypes import *

love = CDLL('libc.so.6')
msg = 'Hello Baby'

love.printf("Testing: %s\n", msg)

Outputs:

Testing: Hello Baby


MS-Windows


from ctypes import *

msvcrt = cdll.msvcrt

msg = 'Hi'

msvcrt.printf('Message: %s', msg)

Outputs:

Message: Hi

Leave a Reply

Your email address will not be published. Required fields are marked *