这个问题类似于How to access with ctypes to functions returning custom types coded in a Delphi dll?。我认为这一点不同之处在于,我正在研究的delphi函数签名将指针作为参数,而不是delphi类型。在
它也类似于Python pass Pointer to Delphi function,除了在评论中提到的那样,这个问题缺少必要的信息。在
如何调用从Python获取并返回自定义类型指针的delphi函数?
我用Python加载一个包含ctypes的DLL来调用delphi函数。在
>>> from ctypes import *
>>> path = "C:\\test.dll"
>>> lib = windll.LoadLibrary(path)
>>> lib.myFunc
<_FuncPtr object at 0x21324905>
delphi函数“myFunc”具有如下签名:
^{pr2}$其中两个指针都应该是自定义数据类型,例如
Type
PSingleArray = ^SingleArray;
SingleArray = Record
LowIndex : SmallInt;
HighIndex : SmallInt;
Data : Array [0..1000] of Single;
end;
通过ctypes tutorial和{a4}似乎解决这个问题的方法是使用“Structure”在Python中创建类似的类型。我认为我做得很好;但是,当我调用myFunc时,会出现一个访问冲突错误。在
>>> class SingleArray(Structure):
>>> _fields_ = [("HighIndex", c_int), ("LowIndex", c_int), ("Data", c_int * 10)]
>>> ...
>>> lib.myFunc.argtypes = [POINTER(SingleArray)]
>>> lib.myFunc.restype = POINTER(SingleArray)
>>> # initialize the input values
>>> input = SingleArray()
>>> a = c_int * 10
>>> data = a(1,2,3,4,5,6,7,8,9,10)
>>> input.Data = data
>>> input.HighIndex = 2
>>> input.LowIndex = 1
>>> # Here comes the access violation error
>>> ret = lib.myFunc(input)
WindowsError: exception: access violation reading 0x00000002
我对ctypes和delphi都是新手,所以我可能会遗漏一些显而易见的东西。在
我可以看到以下几个简单的问题:
Smallint
是有符号的16位类型。最多匹配c_short
。Single
是一个IEEE-754浮点值。最多匹配c_float
。argtypes
和restype
分配不匹配。register
调用约定。这使得函数不可能从其他Delphi模块调用。Result
参数返回的内存,也不清楚如何释放它。更重要的是,结构中的数组似乎是可变长度的。使用ctypes进行封送将非常困难。当然不能使用
Structure._fields_
。在如果可以更改Delphi DLL,请这样做。在当前的形式下,它基本上不能从ctypes中使用。即使是在Delphi代码中,它的使用也是令人震惊的。在
如果您不能更改Delphi DLL,那么我认为您需要用Delphi或FPC编写一个适配器DLL,它为Python代码提供了一个更合理的接口。在
相关问题 更多 >
编程相关推荐