如何使用ctypes访问返回在Delphi dll中编码的自定义类型的函数? [英] How to access with ctypes to functions returning custom types coded in a Delphi dll?

查看:102
本文介绍了如何使用ctypes访问返回在Delphi dll中编码的自定义类型的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个德里DLL,该DLL公开了具有以下签名的函数:

I have a Delhi DLL that is exposing a function with the following signature:

Function MyFunc(ObjID : Cardinal) : TMyRec; stdcall;

其中记录的定义如下:

type TMyRec = record
  Count : Cardinal;
  Items : array of TMyItemRec;
end;

type TMyItemRec = record
  ID : Cardinal;
  Params : array of String;
end;

现在我的问题是:如何获得MyFunc使用Python ctypes调用dll的结果?我编码了两个模拟类型的类

Now my question is: how can I acces results of MyFunc calling the dll with Python ctypes? I coded two classes that mimic the types

from ctypes import *
class TMyItemRec(Structure):
    _fields_ = [("ID", c_int), ("Params", POINTER(c_wchar_p))]

class TMyRec(Structure):
    _fields_ = [("Count", c_int), ("Params", POINTER(TMyItemRec))]

我尝试读取这样的数据:

but when I try to read data like this:

my_dll = windll.Script

def GetMyRec(ID):
    my_dll.MyFunc.argtypes = [c_uint]
    my_dll.MyFunc.restype = TClilocRec

    return my_dll.Script_GetClilocRec(ID)

我遇到访问冲突错误。

推荐答案

您不能将诸如动态数组之类的Delphi托管类型传递给非Delphi代码。您不能期望使用这些数据类型来调用函数。

You cannot pass Delphi managed types like dynamic arrays to non-Delphi code. You cannot expect to call functions with those data types.

您将需要重新设计界面。您需要使用简单类型和包含简单类型的记录。如果需要数组,则必须传递指向第一个元素和长度的指针,而不是使用特定于Delphi的托管类型。将Windows API用作设计互操作接口的模板。

You will need to re-design your interface. You need to use simple types and records containing simple types. If you need arrays then you'll have to pass a pointer to the first element, and the length, rather than using Delphi specific managed types. Use the Windows API as your template for how to design interop interfaces.

您还需要处理的另一件事是,函数返回值在Delphi中的处理方式与在大多数其他Windows编译器中。因此,不适合寄存器的记录将需要作为var参数而不是作为函数返回值传递。

The other thing you'll need to deal with is that function return values are handled differently in Delphi than in most other Windows compilers. So records that do not fit in a register will need to be passed as var parameters rather than as function return values.

这篇关于如何使用ctypes访问返回在Delphi dll中编码的自定义类型的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆