Getting data from ctypes array into numpy

前端 未结 6 800
执念已碎
执念已碎 2020-11-27 02:53

I am using a Python (via ctypes) wrapped C library to run a series of computation. At different stages of the running, I want to get data into Python, and spec

6条回答
  •  再見小時候
    2020-11-27 03:29

    Neither of these worked for me in Python 3. As a general solution for converting a ctypes pointer into a numpy ndarray in python 2 and 3 I found this worked (via getting a read-only buffer):

    def make_nd_array(c_pointer, shape, dtype=np.float64, order='C', own_data=True):
        arr_size = np.prod(shape[:]) * np.dtype(dtype).itemsize 
        if sys.version_info.major >= 3:
            buf_from_mem = ctypes.pythonapi.PyMemoryView_FromMemory
            buf_from_mem.restype = ctypes.py_object
            buf_from_mem.argtypes = (ctypes.c_void_p, ctypes.c_int, ctypes.c_int)
            buffer = buf_from_mem(c_pointer, arr_size, 0x100)
        else:
            buf_from_mem = ctypes.pythonapi.PyBuffer_FromMemory
            buf_from_mem.restype = ctypes.py_object
            buffer = buf_from_mem(c_pointer, arr_size)
        arr = np.ndarray(tuple(shape[:]), dtype, buffer, order=order)
        if own_data and not arr.flags.owndata:
            return arr.copy()
        else:
            return arr
    

提交回复
热议问题