我目前正在从事一个需要访问 DLL 中的函数的项目,我发现 ctypes 可以为我处理函数调用。但是,当某些函数要求通过引用传递参数时,我遇到了一些困难。我试过 ctypes.by_ref() 但它不起作用,因为该对象是用户定义的类。
然后我尝试了 ctypes.pointer(),它吐出错误消息:“type 必须有存储信息”。我想这意味着它只需要 ctypes 数据类型?
我的代码:
from ctypes import *
class myclass():
a= None # requiring c_int32
b= None # requiring c_int32
myci= myclass()
myci.a= c_int32(255)
myci.b= c_int32(0)
mycip= pointer(myci) # let's say it's Line 8 here
loadso= cdll.LoadLibrary(mydll)
Result= loadso.thefunction (mycip) # int thefunction(ref myclass)
终端输出:
Line 8: TypeError: _type_ must have storage info
我想知道 1) 该错误消息是什么意思? 2) 通过引用外部 DLL 解决和传递用户定义类的方法。
提前感谢您的宝贵时间。
请您参考如下方法:
错误消息意味着您无法创建指向非 ctypes 类型的 ctypes 指针。 ctypes 类型具有将值正确编码为 C 所需的信息。
阅读ctypes: Structures and Unions .第一句话是(强调我的):
Structures and unions must derive from the Structure and Union base classes which are defined in the
ctypesmodule.
例如:
>>> from ctypes import *
>>> class Test(Structure):
... _fields_ = [('a',c_int32),
... ('b',c_int16),
... ('c',c_int16)]
...
>>> t = Test(1,2,3)
>>> pointer(t)
<__main__.LP_Test object at 0x00000234A8750A48>
>>> bytes(t)
b'\x01\x00\x00\x00\x02\x00\x03\x00'
请注意,可以采用指针并可以显示结构的原始字节。该结构是小尾数法,为 c_int32 分配了四个字节,为两个 c_int16 成员各分配了两个字节。
