RTC*_*222 6 python arrays ctypes
我使用 ctypes 将数组指针传递给 dll,并返回指向在 dll 中使用 malloc 创建的双精度数组的指针。返回到 Python 后,我需要一种快速方法将指针转换为数组或 Python 列表。
我可以使用此列表比较,但速度很慢,因为有 320,000 个数据点:
list_of_results = [ret_ptr[i] for i in range(320000)]
Run Code Online (Sandbox Code Playgroud)
理想情况下,我会在Python中创建数组并将其传递给dll,但我必须在dll中使用malloc创建它,因为这是一个动态数组,我事先不知道会有多少数据元素(尽管返回指针还返回数据元素的数量,因此我知道返回到 Python 时有多少个)——我使用 realloc 在 dll 中动态扩展数组大小;我可以将 realloc 与 Python 数组一起使用,但最后对 free() 的调用不能保证有效。
Here is the relevant Python code:
CallTest = hDLL.Main_Entry_fn
CallTest.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.c_int64]
CallTest.restype = ctypes.POINTER(ctypes.c_double)
ret_ptr = CallTest(DataArray, number_of_data_points)
list_of_results = [ret_ptr[i] for i in range(320000)]
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:将从 dll 返回的指针转换为 Python 列表或数组的最快方法是什么?上面的方法太慢了。
对 ctypes 数组或指针进行切片将自动生成一个列表:
list_of_results = ret_ptr[:320000]
Run Code Online (Sandbox Code Playgroud)
根据“将指针转换为数组”的含义以及可以使用的输出类型,您也许可以做得更好。例如,您可以直接创建一个由缓冲区支持的 NumPy 数组,无需复制数据:
buffer_as_ctypes_array = ctypes.cast(ret_ptr, ctypes.POINTER(ctypes.c_double*320000))[0]
buffer_as_numpy_array = numpy.frombuffer(buffer_as_ctypes_array, numpy.float64)
Run Code Online (Sandbox Code Playgroud)
如果您在某些东西仍然需要缓冲区时释放缓冲区,这当然会严重破坏。
归档时间: |
|
查看次数: |
5530 次 |
最近记录: |