<小时/>
这个问题类似于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”的签名如下:
Procedure myFunc(Ptr:Pointer;Var Result:Pointer);Export;
两个指针都应该是自定义数据类型,例如
Type
PSingleArray = ^SingleArray;
SingleArray = Record
LowIndex : SmallInt;
HighIndex : SmallInt;
Data : Array [0..1000] of Single;
end;
浏览 ctypes tutorial和 the docs解决这个问题的方法似乎是使用“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 都很陌生,所以我可能会遗漏一些明显的东西。
最佳答案
我可以看到以下简单的问题:
- Delphi
Smallint
是有符号的 16 位类型。最多匹配c_short
。 - Delphi
Single
是一个 IEEE-754 浮点值。最多匹配c_float
。 - Delphi 类型的数组长度为 1001。您的数组长度为 10。
- Delphi 函数有两个参数且无返回值。您的
argtypes
和restype
分配不匹配。 - 您的 ctypes 代码使用 stdcall 调用约定,但 Delphi 函数似乎使用 Delphi 特定的
register
调用约定。这使得该函数无法从除另一个 Delphi 模块之外的任何其他模块调用。 - 谁拥有通过
Result
参数返回的内存,以及如何释放它并不明显。
更重要的是,结构中的数组似乎是可变长度的。使用 ctypes 进行编码将非常棘手。您当然不能使用 Structure._fields_
来做到这一点。
如果您可以更改 Delphi DLL,请这样做。以目前的形式,它基本上无法从 ctypes 中使用。即使是 Delphi 代码,使用起来也很糟糕。
如果您无法更改 Delphi DLL,那么我认为您需要在 Delphi 或 FPC 中编写一个适配器 DLL,为您的 Python 代码提供更合理的接口(interface)。
关于python - 如何调用从 Python 获取并返回自定义类型指针的 delphi 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27925731/