python - What does (ctypes.c_int * len(x))(*x) do? -
i working pyopengl, , opengl requires me transfer data passing pointer , number of bytes transfer.
i understand python doesn't store variables in memory same way c does. have found following code makes program work:
x = [1, 2, ... ] # list (ctypes.c_int * len(x))(*x)
however have no idea why works (and don't want trust haven't gotten lucky how fell memory). code doing?
according python documentation:
the recommended way create concrete array types multiplying ctypes data type positive integer. alternatively, can subclass type , define length , type class variables. array elements can read , written using standard subscript , slice accesses; slice reads, resulting object not array.
example:
>>> ctypes import * >>> tenintegers = c_int * 10 >>> ii = tenintegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) >>> print ii <c_long_array_10 object @ 0x...> >>> in ii: print i, ... 1 2 3 4 5 6 7 8 9 10 >>>
so, first part ctypes.c_int * len(x)
creates array type len(x)
elements:
in [17]: ctypes.c_int * 10 out[17]: __main__.c_int_array_10 in [18]: ctypes.c_int * 100 out[18]: __main__.c_int_array_100
after type creation, should call , pass array elements:
(ctypes.c_int * len(x))(*x) # ^^^^
created array type accepts variadic number of elements, so, should expand list x
using *x
form:
in [24]: x = [1, 2, 3] in [25]: (ctypes.c_int * len(x))(*x) out[25]: <__main__.c_int_array_3 @ 0x7f0b34171ae8> in [26]: list((ctypes.c_int * len(x))(*x)) out[26]: [1, 2, 3] in [27]: (ctypes.c_int * len(x))(*x)[1] out[27]: 2
you cannot pass x
, since __init__
expects integers:
in [28]: (ctypes.c_int * len(x))(x) --------------------------------------------------------------------------- typeerror traceback (most recent call last) <ipython-input-28-ff45cb7481e4> in <module>() ----> 1 (ctypes.c_int * len(x))(x) typeerror: integer required (got type list)
Comments
Post a Comment