[英]Python ctypes: calling a function with custom types in c
我正在嘗試包裝先前存在的C代碼以在Linux中的Python中使用。 我對c的經驗很少,目前正在使用ctypes處理此問題。 我的C函數需要帶有自定義類型條目的2d數組,而且我不知道如何在python中重新創建此數組以將其傳遞給c函數。
這是我嘗試調用的函數:
void usbBuildGainTableAI_USB1808(libusb_device_handle *udev, Calibration_AIN table[NCHAN_1808][NGAINS_1808])
{
int i, j;
uint16_t address = 0x7000; // base address of ADC calibration coefficients.
for (i = 0; i < NCHAN_1808; i++) {
for (j = 0; j < NGAINS_1808; j++) {
usbMemAddressW_USB1808(udev, address);
usbMemoryR_USB1808(udev, (uint8_t *) &table[i][j].slope, sizeof(float));
address += 4;
usbMemAddressW_USB1808(udev, address);
usbMemoryR_USB1808(udev, (uint8_t *) &table[i][j].offset, sizeof(float));
address += 4;
}
}
return;
}
頭文件已定義
typedef struct Calibration_AIN_t {
float slope;
float offset;
} Calibration_AIN;
其中NCHAN_18081和NGAINS_1808是常量,而udev是整數。 我遵循了有關多維數組的一個較舊的問題 ,並試圖在c代碼中創建一種類似於多維數組的結構。
_1808 = CDLL(os.path.abspath("lib1808.so"))
NCHAN_1808 = 8 # max number of A/D channels in the device
NGAINS_1808 = 4 # max number of gain levels
class Calibration_AIN(Structure):
_fields_ = [("slope", c_float), ("offset", c_float)]
class AINarray(Structure):
_fields_ = [("array", (Calibration_AIN() * NCHAN_1808) * NGAINS_1808)]
table_AIN = AINarray()
_1808.usbBuildGainTableAI_USB1808(udev, table_AIN)
但這有兩個問題:不能使用運算符*像int或float那樣將自定義類型Calibration_AIN填充到數組中,並且我無法將自定義類型傳遞給c。 我也嘗試過使用Python中的列表列表來制作數組,但是我無法將其轉換為對c可通過ctypes傳遞的任何有用信息。
如何在不修改C代碼的情況下從python調用此函數? 任何幫助將不勝感激,也請讓我知道我是否應該學習c並嘗試用c或Cython編寫程序。 Ctypes可能不是最好的方法。
該行:
_fields_ = [("array", (Calibration_AIN() * NCHAN_1808) * NGAINS_1808)]
應該實例化 Calibration_AIN ,所以應該引發TypeError 。 我相信您的意思是:
_fields_ = [("array", (Calibration_AIN * NCHAN_1808) * NGAINS_1808)]
但是即使如此,您也不需要AINarray包裝器。 根據[Python]:Arrays ,您可以執行以下操作:
Calibration_AIN_Table = (Calibration_AIN * NCHAN_1808) * NGAINS_1808
然后,為了初始化實例,請執行以下命令:
>>> cat = Calibration_AIN_Table() >>> for i in range(NGAINS_1808): ... for j in range(NCHAN_1808): ... cat[i][j].slope = i * j ... cat[i][j].offset = i * i * j ... >>> cat[2][3].slope 6.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.