2015-09-18 58 views
5

背景如何Python列表傳遞給C函數(DLL)使用ctypes的

我有一些分析軟件在Python我必須通過的4096個字節的列表(它看起來像這樣[80, 56, 49, 50, 229, 55, 55, 0, 77, ......])到dll,以便將dll寫入設備。

  1. 要寫入的字節被存儲在變量名數據
  2. C函數(在DLL),它必須從蟒稱爲是

    int _DLL_BUILD_ IO_DataWrite(HANDLE hDevice, unsigned char* p_pBuff, unsigned char p_nByteCntInBuff);

  3. 我沒有訪問到dll代碼

方法試用

我想聲明的數據類型

data_tx = (ctypes.c_uint8 * len(data))(*data) 

和調用的函數

ret = self.sisdll.IO_DataWrite(self.handle, ctypes.byref(data_tx), ctypes.c_uint8(pending_bytes)) 

問題

似乎沒有錯誤,但它不工作。 API調用與C和C++一起使用。

我是否這樣做是正確的。任何人都可以請爲我指出錯誤嗎?

+0

您是否試過定義參數類型:'IO_DataWrite.argtypes = [c_void_p,POINTER(c_uint8),c_uint8]'? –

+1

通常我會'data_tx =(ctypes.c_uint8 * len(data))()',之後將數據複製到數組中並使用'ctypes.byref'調用庫。你可以試試這個,而不是從數據構造你的數組 –

+0

@JensMunk把它變成一個答案,這是正確的答案 – zwol

回答

5

您試圖實現的目標可以像這樣完成。

接口的頭,說functions.h

#include <stdint.h> 
#include "functions_export.h" // Defining FUNCTIONS_API 
FUNCTIONS_API int GetSomeData(uint32_t output[32]); 

C源,functions.c

#include "functions.h" 
int GetSomeData(uint32_t output[32]) { 
    output[0] = 37; 
} 

在Python中,您只需編寫

import ctypes 
hDLL = ctypes.cdll.LoadLibrary("functions.dll") 
output = (ctypes.c_uint32 * 32)() 
hDLL.GetSomeData(ctypes.byref(output)) 
print(output[0]) 

應該可以看到37號印在屏幕上。

相關問題