ctypes

Utility functions:

ctypes.addressof(obj)
Returns the address of the memory buffer as integer. obj must be an instance of a ctypes type.

ctypes.alignment(obj_or_type)
Returns the alignment requirements of a ctypes type. obj_or_type must be a ctypes type or instance.

ctypes.byref(obj[, offset])
Returns a light-weight pointer to obj, which must be an instance of a ctypes type. offset defaults to zero, and must be an integer that will be added to the internal pointer value.

byref(obj, offset) corresponds to this C code:

(((char *)&obj) + offset)
The returned object can only be used as a foreign function call parameter. It behaves similar to pointer(obj), but the construction is a lot faster.

New in version 2.6: The offset optional argument was added.

ctypes.cast(obj, type)
This function is similar to the cast operator in C. It returns a new instance of type which points to the same memory block as obj. type must be a pointer type, and obj must be an object that can be interpreted as a pointer.

1、addressof與byref關係

>>>str1=c_char_p("hello world")
>>>p1=addressof(str1)
>>>p2=byref(str1)
>>>print hex(p1)
0x107a26a30
>>>print p2
<cparam 'P' (0x107a26a30)>
#其內存地址爲0x107a26a30

2、c_char_p、c_int、pointer內存中形式

>>>str1=c_char_p("hello world")
>>>i1=c_int(3333)
>>>p1=pointer(i1)

str1的內存爲一個指針,指向一個字符串;
i1的內存爲一個整數;
p1的內存爲一個數據結構;

在windbg查看以上對象的內存內容發現c_int的內存形式與c語言的整數形式一樣。c_char_p的內存內容爲一個指針,指針指向一個字符串,而c語言中一個字符串變量的內存內容直接是字符串。pointer對象有其自己結構,其第三個DWORD爲其contents指針,contents內容爲pointer指向對象的指針。假如指向對象爲c_int,則contents中內容爲c_int對象的地址。

>>>str1=c_char_("hello world")
>>>p1=cast(str1,POINTER(c_int))
>>>print p1.contents.value
0x6c6c6568 #爲hell的十六進制形式

假如我們要移位輸出str1的話,那怎麼辦呢?比如獲得“world”這個字符串。

>>>i1=cast(byref(str1),POINTER(c_int))#str1內容是字符串的指針,我們要對此指針進行加操作,先得獲取此指針,就是將其轉換成整數,cast只接受指針,所以先獲取他們的指針,再轉。
>>>offset1=i1.contents.value+6 #加偏移6,便是字符串world的地址,接下來需要將此地址轉成c_char_p
>>>i2=c_int(offset1) #首先得得到它的對象
>>>str2=cast(byref(i2),POINTER(c_char_p)) #將i2轉成c_char_p,由於cast只接受指針,所以先取其指針,再轉。
>>>print str2.contents.value
world

挺無聊,其實就是想通過這個例子弄清楚ctypes中常用類型的類型轉換。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章