【python基础】ctypes使用的变量、指针、引用和buffer

程序如下,学习关注点见备注内容

# -*- 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