我有以下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)
我想在Image构造函数中提供一些语法糖并包装my_image_open
。但是我不能简单地将返回的指针绑定到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]
答案 0 :(得分:1)
所以我最终关注了@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