0
我有以下函數,它接受一個文件名,並返回一個指向Image實例:把ctypes.POINTER(instance)變成一個實際的實例嗎?
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
。不過,我不能簡單地返回的指針綁定到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]
它是複數'argtypes',而不是'argtype'。不,在'__init__'初始化器中調用構造函數是沒有意義的。你必須使用'__new__',但我不推薦它。相反,添加一個替代構造函數作爲'Image.open'' classmethod'。 – eryksun