我使用的ctypes和我定義這個結構,以傳遞參數如何從ctype結構構建python字符串?
class my_struct(ctypes.Structure):
_fields_ = [ ("buffer", ctypes.c_char * BUFSIZE),
("size", ctypes.c_int)]
然後我打電話使用下面的代碼的C函數,但我不知道如何創建從一個字符串我創建的結構體。
class Client():
def __init__(self):
self.__proto = my_struct()
self.client = ctypes.cdll.LoadLibrary(r"I:\bin\client.dll")
def version(self):
ret = self.client.execute(ctypes.byref(self.__proto))
my_string = self.__proto.buffer[:self.__proto.size]
我想用的緩衝區的前n個字節(緩衝區包含NULL字符,但我必須處理這種情況,並與/ 0×00字符,如果necesary建立一個字符串)創建一個Python字符串。灰色
my_string = self.__proto.buffer[:self.__proto.size]
不起作用如果出現0x00,會截斷字符串。任何想法是受歡迎的。提前致謝。
在Python 2.6.3中,我測試過創建一個類似於緩衝區的ctypes數組,但是我無法看到它實際上被截斷了。像這樣:ar =(ctypes.c_char * 10)(); ar.value =「test」; assert ar [:6] =='test \ x00 \ x00'。我錯過了什麼嗎? – aknuds1 2011-02-26 23:52:30