Convert Array pointer to List in Python Ctypes

In this tutorial we will address a common problem faced by many people when trying to convert an Array pointer to a Python list in Ctypes.


Let’s assume we have a C-file with the following code, of which we have also generated a .so file. This code has a single function, which creates an array and returns it back to the Python program (from where we will call this function)

#include <stdio.h>
#include <stdlib.h> 
 
int* getArray() {
    int *array = (int*) malloc(10 * sizeof(int));
    for (int i = 0; i <= 10; i++) {
        array[i] = i;
    }
    return array;
}

The command we use is this (in the command prompt):

gcc -fPIC -shared -o clibrary.so cpplibrary.c

Now we will write our Python code.

import ctypes
import os
 
path = os.getcwd()
clibrary = ctypes.CDLL(os.path.join(path, 'lib.so'))
 
clibrary.getArray.restype = ctypes.POINTER(ctypes.c_int)
x = ctypes.POINTER(ctypes.c_int)
x = clibrary.getArray()

We are storing the return pointer from the C-function in the variable “x”. It is important to remember that you cannot return an entire array, instead what is being returned, is the pointer to the start of the array. (It is also essential to declare “x” as a Ctypes Pointer of type int to store the return pointer properly)

Now what we want to do is somehow convert this to a Python list. So how do we do this? One obvious solution is to do this:

new_list = []
for i in range(10):
    new_list.append(x[i])

But this can be pretty slow when the size of the array is large, and its inefficient. Instead we will make use of indexing and slicing that is commonly used in Python lists.

Here we have done the same thing as before, but in a single and more efficient line of code!

new_list = x[:10]

Note: “10” is the size of the array here.


This marks the end of the Convert Array pointer to List in Python Ctypes Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments