A brief overview of Ctypes in Python for Windows

David E Lares S
Nerd For Tech
Published in
3 min readApr 4, 2024

Are you familiar with Python and C language? Check this resource.

Python Ctypes is like using C code within a Python program. In a few words, they allow you to do things that may not be included in Python.

The formal definition on their official docs states that ctypes is a “foreign function library for Python”, which “provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python”

This is tricky to use and it requires a certain special setup.

If you aren’t familiar with the famous C language, I can tell you that it is the most known low-level programming language (even lower than Python). Most operating systems use it due to its faster characteristics.

C is faster than Python and capable of doing granular work, but the reality is that is harder to use and takes more time to master.

The x86 panorama

The Ctypes use the cdelc and the stdcall functions, and in Windows systems this is called the WindAPI, where the stdcall is used for functions that always take the same number of arguments, it clears the same amount of stack when it returns to you, and the cdelc is used for functions that take a variable number of arguments, when returns, you clean everything up, which means, clean whatever is used.

How about using DLLs?

A DLL is a program used for gaining access to functions from other code, in Python terms, this is similar to a Python module, but with more deep work.

You can use DLLs to use Ctype functions.

In Windows systems, there are three most known major DLLs: kernel32.dll, user32.dll, and msvcrt.dll, whether the first one is responsible for exporting memory management, IO, and process/threads functions. The second one makes the GUI a reality and, of course, makes the OS very user-friendly. And the third one allows programmers to use Linux-C style code without major source-code changes.

A great fit for pointers as well

This whole C pointer advanced functionality can be done with Ctypes too. A pointer, if you don’t know is a memory address reference. As far as I know, Python doesn’t use it. But you can take advantage of it like this

So, things in C like the following can be done:

int a = 0;
int *b = &a;

In C, the int a is the declaration of an integer variable named "a", which points to the 0 value.

And, *b is the pointer definition of the a variable value.

Here’s a working example in Python.

from ctypes import *
a = c_int(1)
string = c_char_p("test \n")
string.value()

These concepts are the most interesting to explore with Ctypes. Of course, there are more concepts involved, mostly related to DLL usage.

Please refer to the official docs here and figure out a proper usage.

--

--