我使用 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 列表或数组的最快方法是什么?上面的方法太慢了。