Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python ctypes uint8 buffer usage

Tags:

python

ctypes

What is the correct way (I am getting seg.fault) to send a uint8 buffer to a C function defined as:

void f(uint8* p, size_t len)

_lib.f.argtypes=[ctypes.POINTER(ctypes.c_ubyte), ctypes.c_uint] 
like image 263
mete Avatar asked Nov 04 '22 06:11

mete


1 Answers

The array objects created by the way you put in your comment - (cbytes.c_ubyte * 256)() are fine. But in ctypes "jargon" this object is not equivalent to a ctypes.POINTER(ctypes.c_ubyte) - ctypes should have warned you when you tried to call the function with the array as a parameter.

Anyway, probably when you pass the created array as the parameter, ctypes is not passing a reference to its contents, but some other thing to C (maybe the address of the Python object, not of its contents).

If you cast a pointer to the contents of your array to the POINTER type you created, it will probably work:

pointer_type = ctypes.POINTER(ctypes.c_ubyte)
_lib.f.argtypes=[pointer_type), ctypes.c_uint] 
data_block = (ctypes.c_ubyte * 256)()
pointer = ctypes.cast(ctypes.addressof(data_block, pointer_type))
_lib.f(pointer, 256)
like image 193
jsbueno Avatar answered Nov 07 '22 23:11

jsbueno