簡體   English   中英

帶有DLL的Python 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)

該函數使用儒略日中的時間進行計算,以將行星體的經度,緯度等返回為兩倍。

我最接近傳遞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函數中獲得所需的加倍,我將永遠感激不已; 我很沮喪,無法解決這個問題。

這(未測試)應該起作用。 第四個參數是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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM