基于ctypes.c_void_p封装C句柄类的可行性及技术问题咨询
关于ctypes封装C句柄API的问题
假设有类似WebRTC VAD的C接口,包含如下函数:
Handler* create(); int process(Handler*); void free(Handler*);
已知可使用ctypes和ctypes.c_void_p表示句柄指针,现咨询以下问题:
- 能否通过继承
ctypes.c_void_p来封装该模式? - 此类的构造函数有何约束?ctypes封送返回句柄时会调用它吗?
- 在派生类
__init__中修改self.value是否正确? - ctypes如何创建
HandlerPointer对象?会调用__init__并影响功能吗? - ctypes是否支持正确封送
c_void_p派生类作为argtypes/restypes? - 有没有更自然的方式表示这类带析构函数的胶囊式对象/API?
示例实现代码
import os import ctypes class HandlerPointer(ctypes.c_void_p): @staticmethod def ffi(lib_path = os.path.abspath('mylib.so')): lib = ctypes.CDLL(lib_path) lib.create.argtypes = [] lib.create.restype = HandlerPointer lib.process.argtypes = [HandlerPointer] lib.process.restype = ctypes.c_int lib.free.argtypes = [HandlerPointer] lib.free.restype = None return lib def __init__(self): super().__init__() self.value = self.lib.create().value def process(self): return self.lib.process(self) def __del__(self): self.lib.free(self) # 不能在类内部初始化这个变量,因为类未初始化时,`.ffi()`中无法引用HandlerPointer HandlerPointer.lib = HandlerPointer.ffi() # 否则会报错
更新说明
__init__方法可正常工作,但__del__调用C的free方法会导致“double free or corruption (!prev)”崩溃,已找到问题,后续将发布完整解决方案。
内容的提问来源于stack exchange,提问作者Vadim Kantorov
相关产品推荐
相关产品推荐

