[英]What is the difference between ctypes.pointer, ctypes.POINTER, and ctypes.byref?
[英]Turning ctypes.POINTER(instance) into an actual instance?
我有以下ctypes
函数,该函数接受文件名并返回指向Image实例的指针:
class Image(ctypes.Structure):
_fields_ = (
('image_info', ImageInfo),
('type', ctypes.c_int),
('format', ctypes.POINTER(Format) ),
)
my_image_open = _lib.my_image_open
my_image_open.argtypes = [ ctypes.c_char_p ]
my_image_open.restype = ctypes.POINTER(Image)
我想提供一些语法糖,并将my_image_open
包装在Image构造函数中。 但是我不能简单地将返回的指针绑定到self
:
class Image(ctypes.Structure):
def __init__( self, filename ):
img = my_image_open( filename )
self = img[0] # does not work, since self is local !
进行上述操作是否有意义,还是我应该只留下一个返回实例的独立函数:
c_image_open = _lib.my_image_open
c_image_open.argtypes = [ ctypes.c_char_p ]
c_image_open.restype = ctypes.POINTER(Image)
# syntactic sugar:
def my_image_open( filename ):
img = c_image_open( filename )
return img[0]
所以我最终遵循了@eryksun的建议:
class Image(ctypes.Structure):
_fields_ = (
('image_info', ImageInfo),
('type', ctypes.c_int),
('format', ctypes.POINTER(Format) ),
)
@classmethod
def open(cls,filename):
img = my_image_open( filename )
if img: return img[0]
return None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.