[Python] ctype 的型態小記




ctype的形式可參考官網

ctypes typeC typePython type
c_bool_Boolbool (1)
c_charchar1-character string
c_wcharwchar_t1-character unicode string
c_bytecharint/long
c_ubyteunsigned charint/long
c_shortshortint/long
c_ushortunsigned shortint/long
c_intintint/long
c_uintunsigned intint/long
c_longlongint/long
c_ulongunsigned longint/long
c_longlong__int64 or long longint/long
c_ulonglongunsigned __int64 or unsigned long longint/long
c_floatfloatfloat
c_doubledoublefloat
c_longdoublelong doublefloat
c_char_pchar * (NUL terminated)string or None
c_wchar_pwchar_t * (NUL terminated)unicode or None
c_void_pvoid *int/long or None
上圖引用自官網

另外標示,如果使用uint_32t等等型態,可利用c_uint32
如果是char的陣列,則可以直接利用char*字串長度

而結構(Struct)的建構則為:


     
from ctype import *

class Structex(Structure):
 _fields_ = [

 ('name', c_char *10), #= c , char[10] 
 ('age', c_int)        #= c , int

 ]


利用_fields_和上表可以簡易做出相對於c語言的Structrue

而要和c的介面做資料擷取時會需要使用到指標(pointer)

     
假設有一函式如下,擷取機器的設定檔,回傳false or ture 表示執行失敗或成功
輸入參數為 自定義的Struct型的指標,擷取完成後會將資料丟入指標結構中
bool GetAllConfig(ConfigStruct *data) 

此時在Python中,便需要利用到pointer函式,另外一個POINTER是專為C_TYPE使用,結構則使用pointer
ex:

Student = Structex()
Student.name = 'testman'
Student.age = 18
PtrStudent = pointer(Student)
這時候就可以利用result = CLL(DLL).GetAllConfig(PtrStudent) 得到資料
取出方法則是
PtrStudent.contents.name -> testman

如果結構中有Pointer的結構 則可以用以下方法初始化 (不限制大小可能出錯)
class name (Structure):
    _fields_=[
         ('name':c_char*16)
]
class PStructure(Structure):
    _fiedls_=[
         ('namep':POINTER(name))
]

PointerList = (name* len(data)() #初始化 data長度的Structure大小
給數值則用 PointerList[0].name = 'test1' ...
簡單的小範例

留言

這個網誌中的熱門文章

[單晶片]-寫I2C通訊(MPU6050為範例)

[單晶片]NEO-6M-0001透過U-center設定簡介

[研發替代役]-威聯通QNAP面試