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

2024-06-16 08:30:49 发布

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


这个问题类似于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都是新手,所以我可能会遗漏一些显而易见的东西。在


Tags: to函数类型inputdataaccesslibmyfunc
1条回答
网友
1楼 · 发布于 2024-06-16 08:30:49

我可以看到以下几个简单的问题:

  • DelphiSmallint是有符号的16位类型。最多匹配c_short
  • DelphiSingle是一个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代码提供了一个更合理的接口。在

相关问题 更多 >