Home > Software engineering >  How to convert a list of numbers to ctpyes array in Python
How to convert a list of numbers to ctpyes array in Python

Time:07-01

I imported a C library into Python and want to use the C function from Python.

The data in Python is saved in a list, for example: user_data = [1, 255, 30, 100, 0, 12, 5, 216]. All elements in the list are numbers (0..255). I need to convert this number list to ctypes so that it can be input into the C function below.

The C function I will use is int c_function(unsigned char* bytes); where the input argument is a pointer to an array of numbers. Note the input value is an array of numbers rather than an array of characters / a string, which means 0 is a normal number instead of a NUL termination character.

How can I convert a number list to a number array (more precisely, a pointer to a number array) in ctypes?

CodePudding user response:

you can do this

import ctypes
user_data = [1, 255, 30, 100, 0, 12, 5, 216]
arr = (ctypes.c_int * len(user_data))(*user_data)

this will convert the list into ctypes

CodePudding user response:

If you want 0 to just be a normal number, then you need another argument to your C function so that it knows how long the array is. For the sake of a concrete example, I'll go with this as your C function:

#include <stddef.h>

int c_function(unsigned char *bytes, size_t len) {
    int sum = 0;
    for(size_t i = 0; i < len;   i) {
        sum  = bytes[i];
    }
    return sum;
}

Compile that with gcc -fPIC -shared q72815146.c -o q72815146.so, then do this in Python:

from ctypes import *

mydll = CDLL("./q72815146.so")
mydll.c_function.restype = c_int
mydll.c_function.argtypes = (POINTER(c_ubyte), c_size_t)

def c_function(x):
    l = len(x)
    return mydll.c_function((c_ubyte * l)(*x), l)

user_data = [1,255,30,100,0,12,5,216]
print(c_function(user_data))
  • Related