Python通过引用dll传递用户定义的类

2024-05-16 18:03:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在做一个需要访问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)

终端输出:

^{pr2}$

我想知道1)那个错误信息是什么意思?以及2)通过引用外部DLL来处理和传递用户定义类的方法。在

提前感谢您抽出时间。在


Tags: 函数用户noneref定义myclassctypesdll
1条回答
网友
1楼 · 发布于 2024-05-16 18:03:19

错误消息表示您不能创建指向非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 ctypes module.

例如:

>>> 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'

注意,可以使用指针,并且可以显示结构的原始字节。该结构是little-endian,为c_int32分配了4个字节,为两个c_int16成员分别分配了两个字节。在

相关问题 更多 >