Python 使ctype char/char数组和派生char/char数组的行为类似
我正在更新包含Python 使ctype char/char数组和派生char/char数组的行为类似,python,python-2.7,ctypes,Python,Python 2.7,Ctypes,我正在更新包含ctypes.c_char和ctypes.c_char数组字段的ctype结构,以便现在使用派生类型。为了方便用户,我想让包含这些c_char字段的ctype结构像其他ctype数组一样工作。例如,当访问ctypes.c_ubyte*5数组时,用户仍然可以访问ctype数组,但当访问ctypes.c_char*5数组时,您只能获得Python字符串 以下是我的一些示例结构: import ctypes class chr(ctypes.c_char): pass clas
ctypes.c_char
和ctypes.c_char
数组字段的ctype结构,以便现在使用派生类型。为了方便用户,我想让包含这些c_char
字段的ctype结构像其他ctype数组一样工作。例如,当访问ctypes.c_ubyte*5
数组时,用户仍然可以访问ctype数组,但当访问ctypes.c_char*5
数组时,您只能获得Python字符串
以下是我的一些示例结构:
import ctypes
class chr(ctypes.c_char):
pass
class str(ctypes.Array):
_type_ = chr
_length_ = 5
class old_struct(ctypes.Structure):
_fields_ = [('str', ctypes.c_char * 5), ('char', ctypes.c_char)]
class new_struct(ctypes.Structure):
_fields_ = [('str', str), ('char', chr)]
访问这些字段时,我得到:
old = old_struct()
print old.str # ''
print old.char # '\x00'
new = new_struct()
print new.str # ''
print new.char # <chr object at ...>
print new.char.value # '\x00'
old=old_struct()
打印old.str#“”
打印old.char#'\x00'
新建=新建结构()
打印new.str#“”
打印new.char#
打印新的.char.value#'\x00'
如何使new.str
像现在一样工作,同时还包含一个value
datamember,当访问该成员时,它将返回包含的Python字符串。如果用户访问new.str
而未指定value
(即new.str.value
),我还希望显示一个弃用警告。
我还希望
new.char
能够像old.char
一样向后兼容,但同时保留其当前功能。如果用户访问new.char
而未指定value
(即new.char.value
),我希望显示一个弃用警告 c_char
和c_wchar
数组类型的字段描述符使用GETFUNC
和SETFUNC
。这是在(第107行)中配置的。您需要将字段设置为私有,例如\u str
,然后创建一个str
属性,该属性返回数组子类的实例。您可以基于结构地址加上字段偏移量使用数组的from\u address
构造函数,例如str.from\u address(addressof(self)+type(self)。\u str.offset)
。