Archive for the ‘C’ Category

Arrays in ctypes

In ctypes an array is defined by multiplying a type by the number of elements you want allocated within the array, for example:

In Python
class marijuana_amount(Union):
    _fields_ = [
    ("weed_long", c_long),
    ("weed_int", c_int),
    ("weed_char", c_char * 8),


Definition: unions in C and Python

Unions are basically the same as structs except that in a union all variables have the same memory location. This makes it easy to store the same value in different datatypes.


Definition: struct

In both C and Python a struct, or structure, is simply a group of variables of homogenous or heterogeneous datatypes which can be accessed using dot notation (e.g. group.var, indoctrinator.victim, ford.mustang, etc).



In C:

struct conspiracy
 int corrupt_police
 int corrupt_medics

In Python:

class conspiracy(Structure):
    _fields_ = [
 ("corrupt_police", c_int),
 ("corrupt_medics", c_int),





C-Python-ctypes Data Type Mapping Table

data type map c python ctypes

Quick-Tip: 3 Ways to Load Ctypes in Python

  1. cdll()
  2. windll()
  3. oledll()


cdecl and stdcall Calling Conventions, Stack Clearing and the EAX Register

Two key calling conventions are:

1. cdecl
2. stdcall

In cdecl parameters are pushed from right to left and the caller of the function is responsible for clearing the arguments from the stack. Used by most C systems on the x86 architecture.
Example of a cdecl call in C:
 int python_rocks(reason_one, reason_two, reason_three); 
In x86 Assembly:

push reason_three
push reason_two
push reason_one
call python_rocks
add esp, 12

The last line above increments the stack pointer 12 bytes (there are 3 parameters to the function and each stack parameter is 4 bytes and thus 12 bytes) which essentially clears those parameters.
Example of a stdcall call in C:

int my_socks(color_one, color_two, color_three);

In x86 Assembly:

push color_three
push color_two
push color_one
call my_socks
The order of the parameters in stdcall is the same but the stack clearing is not done by the caller, but by the my_socks function.
For both stdcall and cdecl calling conventions it’s important to note that return values are stored in the EAX register.