程序如下,學習關注點見備注內容
# -*- coding: utf-8 -*-
from ctypes import *
import sys
print '-'*100
python_str = 'tests中國人' # 中文占4字節
print 'python_string', python_str
print 'len:', len(python_str) # 字符長度,中文占3個長度,不含類似於C語言的結束符
print 'getsizeof', sys.getsizeof(python_str)
# print 'byref', byref(python_str) # byref參數必須是ctypes類型
# print 'sizeof', sizeof(python_str) # sizeof參數必須是ctypes類型
print '-'*100
c_str_p = c_char_p(python_str)
print 'c_str_p', c_str_p
# print 'len:', len(c_str_p) # pointer沒有len
print 'getsizeof', sys.getsizeof(c_str_p) # 整個對象在python中占用的字節數
print 'sizeof', sizeof(c_str_p) # 指針地址占用的字節數
print 'addressof', hex(addressof(c_str_p)) # 純地址
print 'byref', byref(c_str_p) # 引用指針
print 'string_at', string_at(c_str_p) # 獲取內容
print 'string_at 0-4', string_at(c_str_p, 4) # 獲取內容
print '-'*100
c_str_buffer = c_buffer(python_str)
print 'c_str_buffer', c_str_buffer
print 'getsizeof', sys.getsizeof(c_str_buffer)
print 'sizeof', sizeof(c_str_buffer) # 字節數, 一個中文字符占3個字節,一個英文字符占1個字節,結束符占一個字節
print 'addressof', hex(addressof(c_str_buffer)) # 純地址
print 'byref', byref(c_str_buffer) # 引用指針
print 'c_str_buffer.value', c_str_buffer.value # 獲取內容
print 'c_str_buffer[:4]', c_str_buffer[:4] # 截取內容
print '-'*100
c_num_long = c_long(0xfff)
print 'c_num_long', c_num_long # 對象本身
print 'value', c_num_long.value # 值
print 'sizeof', sizeof(c_num_long)
print '-'*100
c_num_int = c_int(123)
print 'c_num_int', c_num_int # 對象本身
print 'value', c_num_int.value # 值
print 'sizeof', sizeof(c_num_int)
print '-'*100
c_num_int64 = c_int64(123)
print 'c_num_int64', c_num_int64 # 對象本身
print 'value', c_num_int64.value # 值
print 'sizeof', sizeof(c_num_int64)
運行結果
C:\Python27\python.exe C:/code/cetc/engine/DistributedNode/test.py
----------------------------------------------------------------------------------------------------
python_string tests中國人
len: 14
getsizeof 47
----------------------------------------------------------------------------------------------------
c_str_p c_char_p('tests\xe4\xb8\xad\xe5\x9b\xbd\xe4\xba\xba')
getsizeof 128
sizeof 8
addressof 0x24f8a10L
byref <cparam 'P' (00000000024F8A10)>
string_at tests中國人
string_at 0-4 test
----------------------------------------------------------------------------------------------------
c_str_buffer <ctypes.c_char_Array_15 object at 0x00000000024F8A48>
getsizeof 128
sizeof 15
addressof 0x24f8a90L
byref <cparam 'P' (00000000024F8A90)>
c_str_buffer.value tests中國人
c_str_buffer[:4] test
----------------------------------------------------------------------------------------------------
c_num_long c_long(4095)
value 4095
sizeof 4
----------------------------------------------------------------------------------------------------
c_num_int c_long(123)
value 123
sizeof 4
----------------------------------------------------------------------------------------------------
c_num_int64 c_longlong(123L)
value 123
sizeof 8
Process finished with exit code 0