Here's a quick and dirty ctypes tutorial.

First, write your C library. Here's a simple Hello world example:

testlib.c

#include <stdio.h>

void myprint(void);

void myprint()
{
    printf("hello world\n");
}

Now compile it as a shared library (mac fix found here):

$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c

# or... for Mac OS X 
$ gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC testlib.c

Then, write a wrapper using ctypes:

testlibwrapper.py

import ctypes

testlib = ctypes.CDLL('/full/path/to/testlib.so')
testlib.myprint()

Now execute it:

$ python testlibwrapper.py

And you should see the output

Hello world
$

If you already have a library in mind, you can skip the non-python part of the tutorial. Make sure ctypes can find the library by putting it in /usr/lib or another standard directory. If you do this, you don't need to specify the full path when writing the wrapper. If you choose not to do this, you must provide the full path of the library when calling ctypes.CDLL().

This isn't the place for a more comprehensive tutorial, but if you ask for help with specific problems on this site, I'm sure the community would help you out.

PS: I'm assuming you're on Linux because you've used ctypes.CDLL('libc.so.6'). If you're on another OS, things might change a little bit (or quite a lot).

Answer from Chinmay Kanchi on Stack Overflow
🌐
Python
docs.python.org › 3 › library › ctypes.html
ctypes — A foreign function library for Python
Source code: Lib/ctypes ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these ...
Top answer
1 of 4
279

Here's a quick and dirty ctypes tutorial.

First, write your C library. Here's a simple Hello world example:

testlib.c

#include <stdio.h>

void myprint(void);

void myprint()
{
    printf("hello world\n");
}

Now compile it as a shared library (mac fix found here):

$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c

# or... for Mac OS X 
$ gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC testlib.c

Then, write a wrapper using ctypes:

testlibwrapper.py

import ctypes

testlib = ctypes.CDLL('/full/path/to/testlib.so')
testlib.myprint()

Now execute it:

$ python testlibwrapper.py

And you should see the output

Hello world
$

If you already have a library in mind, you can skip the non-python part of the tutorial. Make sure ctypes can find the library by putting it in /usr/lib or another standard directory. If you do this, you don't need to specify the full path when writing the wrapper. If you choose not to do this, you must provide the full path of the library when calling ctypes.CDLL().

This isn't the place for a more comprehensive tutorial, but if you ask for help with specific problems on this site, I'm sure the community would help you out.

PS: I'm assuming you're on Linux because you've used ctypes.CDLL('libc.so.6'). If you're on another OS, things might change a little bit (or quite a lot).

2 of 4
78

The answer by Chinmay Kanchi is excellent but I wanted an example of a function which passes and returns a variables/arrays to a C++ code. I though I'd include it here in case it is useful to others.

Passing and returning an integer

The C++ code for a function which takes an integer and adds one to the returned value,

extern "C" int add_one(int i)
{
    return i+1;
}

Saved as file test.cpp, note the required extern "C" (this can be removed for C code). This is compiled using g++, with arguments similar to Chinmay Kanchi answer,

g++ -shared -o testlib.so -fPIC test.cpp

The Python code uses load_library from the numpy.ctypeslib assuming the path to the shared library in the same directory as the Python script,

import numpy.ctypeslib as ctl
import ctypes

libname = 'testlib.so'
libdir = './'
lib=ctl.load_library(libname, libdir)

py_add_one = lib.add_one
py_add_one.argtypes = [ctypes.c_int]
value = 5
results = py_add_one(value)
print(results)

This prints 6 as expected.

Passing and printing an array

You can also pass arrays as follows, for a C code to print the element of an array,

extern "C" void print_array(double* array, int N)
{
    for (int i=0; i<N; i++) 
        cout << i << " " << array[i] << endl;
}

which is compiled as before and the imported in the same way. The extra Python code to use this function would then be,

import numpy as np

py_print_array = lib.print_array
py_print_array.argtypes = [ctl.ndpointer(np.float64, 
                                         flags='aligned, c_contiguous'), 
                           ctypes.c_int]
A = np.array([1.4,2.6,3.0], dtype=np.float64)
py_print_array(A, 3)

where we specify the array, the first argument to print_array, as a pointer to a Numpy array of aligned, c_contiguous 64 bit floats and the second argument as an integer which tells the C code the number of elements in the Numpy array. This then printed by the C code as follows,

1.4
2.6
3.0
🌐
7-Zip Documentation
documentation.help › Python-v2.7.2 › ctypes.html
15.18. ctypes — A foreign function library for Python - Python v2.7.2 Documentation
June 12, 2011 - None is passed as a C NULL pointer, byte strings and unicode strings are passed as pointer to the memory block that contains their data (char * or wchar_t *). Python integers and Python longs are passed as the platforms default C int type, their value is masked to fit into the C type. Before we move on calling functions with other parameter types, we have to learn more about ctypes data types.
🌐
Medium
medium.com › nerd-for-tech › a-brief-overview-of-ctypes-in-python-windows-4e205484ff8a
A brief overview of Ctypes in Python for Windows | by David E Lares S | Nerd For Tech | Medium
July 22, 2024 - 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.
🌐
Pendancer
python.pendancer.com › advanced › ctypes.html
CTypes and Structures - Python
CTypes provide C compatible data types and allow function calls from DLLs or shared libraries without having to write custom C extensions for every operation. So we can access the functionality of a C library from the safety and comfort of the Python Standard Library.
🌐
Guidetopython
en.guidetopython.com › home › index › ctypes
Python ctypes - Stdlib — Misc | Guide to Python
Learn Python ctypes: Call functions in C shared libraries directly from Python. Interactive examples, playground, and documentation.
🌐
Beautiful Soup
tedboy.github.io › python_stdlib › generated › generated › ctypes.CDLL.html
ctypes.CDLL — Python Standard Library
ctypes » · ctypes.CDLL · View page source · class ctypes.CDLL(name, mode=0, handle=None, use_errno=False, use_last_error=False)[source]¶ · An instance of this class represents a loaded dll/shared library, exporting functions using the standard C calling convention (named ‘cdecl’ on ...
Find elsewhere
🌐
Python
svn.python.org › projects › ctypes › trunk › ctypes › docs › manual › tutorial.html
ctypes tutorial
None is passed as a C NULL pointer, byte strings and unicode strings are passed as pointer to the memory block that contains their data (char * or wchar_t *). Python integers and Python longs are passed as the platforms default C int type, their value is masked to fit into the C type. Before we move on calling functions with other parameter types, we have to learn more about ctypes data types.
🌐
Cheater.fun
cheater.fun › cs 2
Download Free CS2 Hacks – Aimbot, Wallhack, ESP & More | Safe & Updated
- Updated walk bot to be completely reliant on ctypes, no more psutil. UNDETECTED · Version: 36 Developer: owner tkazer, fix by hitcommunity · The file is verified and available for download · December 7, 2025 · 159 288 · 245 · - Updated Offsets (Build: December 7, 2025) OUTDATED ·
🌐
GitHub
github.com › python › cpython › blob › main › Modules › _ctypes › _ctypes.c
cpython/Modules/_ctypes/_ctypes.c at main · python/cpython
Convert a Python object into a function call parameter. ... _validate_paramflags(ctypes_state *st, PyTypeObject *type, PyObject *paramflags, PyObject *argtypes);
Author   python
🌐
7-Zip Documentation
documentation.help › IronPython › ctypes.html
15.16. ctypes — A foreign function library for Python - IronPython Documentation
May 10, 2013 - None is passed as a C NULL pointer, byte strings and unicode strings are passed as pointer to the memory block that contains their data (char * or wchar_t *). Python integers and Python longs are passed as the platforms default C int type, their value is masked to fit into the C type. Before we move on calling functions with other parameter types, we have to learn more about ctypes data types.
🌐
Python
svn.python.org › projects › ctypes › branches › ctypes-1.1 › docs › manual › reference.html
ctypes reference
It can be used to wrap these libraries in pure Python. ... When programming in a compiled language, shared libraries are accessed when compiling/linking a program, and when the program is run. The purpose of the find_library function is to locate a library in a way similar to what the compiler does (on platforms with several versions of a shared library the most recent should be loaded), while the ctypes library loaders act like when a program is run, and call the runtime loader directly.
🌐
PyPI
pypi.org › project › pygame
pygame · PyPI
Pygame is obviously strongly dependent on SDL and Python. It also links to and embeds several other smaller libraries. The font module relies on SDL_ttf, which is dependent on freetype. The mixer (and mixer.music) modules depend on SDL_mixer. The image module depends on SDL_image, which also ...
      » pip install pygame
    
Published   Sep 29, 2024
Version   2.6.1
🌐
W3Schools
w3schools.com › Python › ref_module_ctypes.asp
Python ctypes Module
Python Examples Python Compiler ... Certificate Python Training ... The ctypes module provides C compatible data types and allows calling functions in DLLs/shared libraries....
🌐
Medium
medium.com › @nimratahir1212 › python-interface-that-uses-ctypes-to-load-and-call-ebc5874254c3
Python Interface that uses Ctypes to load and Call | by Nimra Tahir | Medium
April 16, 2023 - Python Interface that uses Ctypes to load and Call Here is an example Python interface that uses ctypes to load and call a C function: Sample Code: import ctypes # Load the shared library mylib = …
🌐
CodersLegacy
coderslegacy.com › home › python › python ctypes tutorial
Python ctypes Tutorial - CodersLegacy
October 27, 2022 - In this Python Tutorial, we will be discussing the ctypes library. The ctypes library allows us to use functions from the C language which...
🌐
Medium
medium.com › @datasciencefilmmaker › my-god-its-full-of-stars-2-7-accessing-c-structures-in-python-using-ctypes-d75d01d2cb94
My God, It’s Full of Stars (2/7) — Accessing C Structures in Python Using Ctypes | by Data Science Filmmaker | Medium
January 18, 2024 - It makes extensive use of structures and pointers to make accessing memory more efficient than the equivalent object-oriented version, and way more efficient than the Python equivalent would be. I wanted to take advantage of the speed of C while still using mostly Python syntax. Enter the “ctypes” library.
🌐
SageMath
doc.sagemath.org › html › en › thematic_tutorials › numerical_sage › ctypes_examples.html
More complicated ctypes example - Thematic Tutorials
Next consider the following python helper code. from ctypes import * class double_row_element(Structure): pass double_row_element._fields_=[("value",c_double),("col_index",c_int),("next_element",POINTER(double_row_element) )] class double_sparse_matrix(Structure): _fields_=[("nrows",c_int),("ncols",c_int),("nnz",c_int),("rows",POINTER(POINTER(double_row_element)))] double_sparse_pointer=POINTER(double_sparse_matrix) sparse_library=CDLL("/home/jkantor/linked_list_sparse.so") initialize_matrix=sparse_library.initialize_matrix initialize_matrix.restype=double_sparse_pointer set_value=sparse_library.set_value get_value=sparse_library.get_value get_value.restype=c_double free_matrix=sparse_library.free_matrix
🌐
Readthedocs
scipy-cookbook.readthedocs.io › items › Ctypes.html
Ctypes — SciPy Cookbook documentation
May 5, 2006 - It is included in the standard library for Python 2.5. ctypes allows to call functions exposed from DLLs/shared libraries and has extensive facilities to create, access and manipulate simple and complicated C data types in Python - in other words: wrap libraries in pure Python.