【问题标题】:Python ctypes arguments with DLL - pointer to array of doubles带有 DLL 的 Python ctypes 参数 - 指向双精度数组的指针
【发布时间】:2018-06-23 14:58:27
【问题描述】:

我是一个在 Python 中使用 ctypes 的新手编码器,并尝试使用用 C 编写的 DLL 中的函数。我发现了很多类似的问题,但没有任何东西可以回答这种类型的难题。

我已经很好地加载了 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)

该函数使用儒略日中的时间进行计算,以双精度形式返回行星体的经度、纬度等。

我最接近传递 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 函数中获得所需的双精度,我将永远感激不尽;我被难住了,无法把它搞定。

【问题讨论】:

    标签: python c dll ctypes


    【解决方案1】:

    这(未经测试)应该可以工作。第四个参数是类型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)
    

    【讨论】:

    • 这是我正在寻找的答案;工作就像一个魅力,我对这段代码的了解比我今天想象的要深得多。谢谢!
    • 回答已接受,感谢您提醒我注意!对不起!
    猜你喜欢
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    相关资源
    最近更新 更多