python - 如何调用从 Python 获取并返回自定义类型指针的 delphi 函数?

标签 python delphi pointers dll ctypes

<小时/>

这个问题类似于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 tutorialthe 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 函数有两个参数且无返回值。您的 argtypesrestype 分配不匹配。
  • 您的 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/

相关文章:

Python:为 Ansible 编写 INI 文件

python - 从 url 获取图像时出错

python - 将数据库数据导入 Joomla

delphi - 我可以使用一个命令从一个特定字段获取所有记录吗?

sql - Delphi 中 TADOStoredProc.ProcedureName 值中的 "*;1"是什么?

python - 如何在给定区间值的区间内进行随机抽样?

delphi - IDE:结构查看器显示所有展开的项目

C——指向指针数组的指针

c++ - 使用bool函数在c++中进行递归二进制搜索

c - 使用两个函数生成随机数数组