Corresponding type ctypes numpy.dtype?

If I have a numpy ndarray with a specific dtype , how do I know what matches the ctypes type?

For example, if I have ndarray, I can do the following to convert it to a shared array:

 import multiprocessing as mp import numpy as np import ctypes x_np = np.random.rand(10, 10) x_mp = mp.Array(ctypes.c_double, x_np) 

However, here I have to specify c_double . It works if I do not specify the same type, but I would like to keep the type the same. How can I find out the ctypes ndarray x_np x_np automatically, at least for some common elementary data types?

+10
source share
2 answers

There is actually a way to do this built into Numpy :

 x_np = np.random.rand(10, 10) typecodes = np.ctypeslib._get_typecodes() typecodes[x_np.__array_interface__['typestr']] 

Output:

 ctypes.c_double 

np.ctypeslib._get_typecodes means that the np.ctypeslib._get_typecodes function np.ctypeslib._get_typecodes marked as private (i.e. np.ctypeslib._get_typecodes name starts with _ ). However, its implementation does not seem to have changed over time, so you can probably use it reliably enough.

Alternatively, the implementation of _get_typecodes rather short, so you can simply copy the entire function into your own code:

 import ctypes import numpy as np def get_typecodes(): ct = ctypes simple_types = [ ct.c_byte, ct.c_short, ct.c_int, ct.c_long, ct.c_longlong, ct.c_ubyte, ct.c_ushort, ct.c_uint, ct.c_ulong, ct.c_ulonglong, ct.c_float, ct.c_double, ] return {np.dtype(ctype).str: ctype for ctype in simple_types} 
+1
source

Now this is supported by np.ctypeslib.as_ctypes_type() :

 import numpy as np x_np = np.random.rand(10, 10) np.ctypeslib.as_ctypes_type(x_np.dtype) 

Gives ctypes.c_double , as expected.

+1
source

Source: https://habr.com/ru/post/1234156/


All Articles