You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python4Delphi使用TPyDelphiWrapper.WrapInterface封装Delphi接口访问属性报错

问题原因

你使用WrapInterface封装接口时出错的核心原因是自定义接口未提前向TPyDelphiWrapper注册类型信息:

  • WrapInterface是专门用于封装Delphi/COM接口的方法,它依赖你主动注册的接口RTTI(运行时类型信息)来识别接口的属性、方法成员。你只定义了IPerson、ICustomer、ISupplier三个接口,但没有注册,所以Python侧识别不到接口的属性,就会抛出Unknown attribute报错。
  • 而你直接调用Wrap方法时,方法会自动获取接口对应的实现类实例(也就是TPerson/TCustomer等类的对象),TPyDelphiWrapper默认会自动识别Delphi类的公开成员,所以不需要额外注册就能正常访问属性。

正确使用WrapInterface的方法

如果你的场景需要只暴露接口、隐藏实现类细节,可以在封装接口前先注册自定义接口的类型信息,示例代码如下:

procedure TFrmTestInterface.FormCreate(Sender: TObject);
var
  LPerson : IPerson;
  LCustomer : ICustomer;
  LSupplier : ISupplier;
  Py: PPyObject;
begin
  // 新增:提前注册自定义接口的类型信息
  PyDelphiWrapper1.RegisterInterface(TypeInfo(IPerson));
  PyDelphiWrapper1.RegisterInterface(TypeInfo(ICustomer));
  PyDelphiWrapper1.RegisterInterface(TypeInfo(ISupplier));

  // 后续的初始化、封装逻辑保持不变
  LPerson := TPerson.Create;
  LCustomer := TCustomer.Create;
  LSupplier := TSupplier.Create;

  LPerson.Name := 'Pippo';
  LPerson.Surname := 'Rossi';

  LCustomer.Name := 'Pluto';
  LCustomer.Surname := 'Verdi';

  LSupplier.Name := 'Paperino';
  LSupplier.Surname := 'Bianchi';


  Py := PyDelphiWrapper1.WrapInterface(TValue.From(LPerson));
  PythonModule1.SetVar('delphi_person', Py);
  GetPythonEngine.Py_DecRef(Py);

  Py := PyDelphiWrapper1.WrapInterface(TValue.From(LCustomer));
  PythonModule1.SetVar('delphi_customer', Py);
  GetPythonEngine.Py_DecRef(Py);

  Py := PyDelphiWrapper1.WrapInterface(TValue.From(LSupplier));
  PythonModule1.SetVar('delphi_supplier', Py);
  GetPythonEngine.Py_DecRef(Py);
end;

注册完成后再运行Python脚本,就能正常访问接口定义的属性了。


内容的提问来源于stack exchange,提问作者filippocurati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 05:39:04