Python 带 DLL 的 ctypes 参数 - 指向双精度数组的指针

Python ctypes arguments with DLL - pointer to array of doubles

我是一名新手编码员,在 Python 中使用 ctypes,并尝试使用用 C 编写的 DLL 中的函数。我在 SO 上发现了很多类似的问题,但没有一个能回答这种类型难题。

我已经很好地加载了 DLL,但是我需要调用的函数之一要求一个指向 6 个双精度数组的指针以将值转储到其中,我不知道如何为函数提供它需要的东西通过 Python。 (我在 C 中尝试这样做的失败是另一回事。)

我尝试了 ctypes.POINTER(c_double) 的各种排列,使用 byref()、POINTER(c_double * 6) 等,最坏的情况下我会遇到类型错误,或充其量访问冲突,对于所有这些。

来自 DLL 文档:

int swe_calc_ut (double tjd_ut, int ipl, int iflag, double* xx, char* serr)

该函数使用儒略日的时间对return行星体的经度、纬度等进行双倍计算。

我最接近于传递 DLL 将接受的数据类型是使用此代码,只是试图从 swe_calc_ut:

中获取 6 个双打中的任何一个
dll = windll.LoadLibrary(# file path)

# retype the args for swe_calc_ut
py_swe_calc_ut = dll.swe_calc_ut
py_swe_calc_ut.argtypes = [c_double, c_int, c_int, c_double, c_char_p]
py_swe_calc_ut.restype = None

tjd = c_double(# some value from elsewhere)

returnarray = c_double()
errorstring = create_string_buffer(126)

py_swe_calc_ut(tjd, c_int(0), c_int(64*1024), returnarray, errorstring)

当我按原样尝试 运行 时,出现错误:

OSError: exception: access violation writing 0x0000000000000000

使用 byref() 给我一个类型错误等

如果有人能指出正确的方向以从原始 DLL 函数中获得所需的双打,我将永远感激;我很困惑,无法将其付诸实践。

这个(未经测试)应该有效。第 4 个参数类型为 POINTER(c_double)。 C 的 double returnarray[6] 类型的等价物是 c_double * 6 并且该类型的实例是 returnarray= (c_double * 6)()。此外,如果您已经声明了参数类型,则不需要包装输入参数,例如 int(0);通过 0 没问题:

dll = windll.LoadLibrary(# file path)

# retype the args for swe_calc_ut
py_swe_calc_ut = dll.swe_calc_ut
py_swe_calc_ut.argtypes = [c_double, c_int, c_int, POINTER(c_double), c_char_p]
py_swe_calc_ut.restype = None

tdj = 1.5 # some value
returnarray = (c_double * 6)()
errorstring = create_string_buffer(126)

py_swe_calc_ut(tjd, 0, 64*1024, returnarray, errorstring)