How to access with ctypes to functions returning custom types coded in a Delphi dll?

折月煮酒 提交于 2020-02-03 16:45:31

问题


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

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

where the records are defined so:

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

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

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)

I get access violation error.


回答1:


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

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.

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.



来源:https://stackoverflow.com/questions/17285515/how-to-access-with-ctypes-to-functions-returning-custom-types-coded-in-a-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!