我在获取指向结构工作的指针时遇到问题。这是引发异常“ArgumentError:argument 1::应为LP_LP_List instance而不是指向LP_LP_List的指针”的代码。
class List(Structure):
_fields_ = (
('head', POINTER(Node)),
('tail', POINTER(Node)),
('current', POINTER(Node)),
('saved', POINTER(Node)),
('infosize', c_int),
('listsize', c_ulong),
('current_index', c_ulong),
('save_index', c_ulong),
('modified', c_bool),
('search_origin', c_int),
('search_dir', c_int),
)
list_p = POINTER(List)
create = lib.DLL_CreateList
create.argtypes = [POINTER(POINTER(List)),]
create.restype = POINTER(List)
mem = POINTER(list_p)()
retval = create(byref(mem))
这似乎遵循了推荐的方法,但不起作用。
谢谢你的帮助。
对于那些不想阅读下面所有细节以找到解决方案的人,最后一部分应该如下所示:
#list_p = POINTER(List) # Not needed
create = lib.DLL_CreateList
create.argtypes = [POINTER(POINTER(List)),]
create.restype = POINTER(List)
control = POINTER(List)()
list_p = create(byref(control))
API听起来像通过引用传入的指针将被create修改,因此它必须通过引用传入,返回值是新创建的列表。
如果这是用“C”写的,我猜你会有这样的代码:
对于ctypes/Python,这将映射到:
这样更好吗?
编辑: 由于create both修改传入的参数并且返回创建的列表,所以我忘记了返回,只保留参数:
为了保证Python API的完整性,您可以考虑编写一个上下文管理器来调用Create(当上下文管理器的
__enter__
方法被with
语句调用以初始化列表控制块时),并自动调用Destroy(当上下文管理器的__exit__
方法在with
语句的作用域末尾调用时)。那么您的Python代码可能如下所示:编辑:-我在Ubuntu上建立了你的DLL,并使用了上面的Python代码,看起来它毕竟列出了一个列表。
编辑-我编写了一个pyparsing实用程序来读取C头文件并输出占位符结构子类、函数argtypes和restype定义。下面是我为你的lib准备的——它还未测试,但可能会让你在API测试中有一个新的开始:
相关问题 更多 >
编程相关推荐