Delphi – 每个名称调用Record方法

前端之家收集整理的这篇文章主要介绍了Delphi – 每个名称调用Record方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我为我的应用程序编写了一个脚本语言,我的目标是可以在脚本中发布delphi中的任何类型.我使用rtti来自动执行此任务.对于像类这样的任何实例类型,我使用以下代码从脚本中查找并调用方法.
  1. var Info : TRttiType;
  2. Meth : TRttiMethod;
  3. Param : TArray<TValue>;
  4. Result : TValue;
  5. AnyClass : TClass;
  6. begin
  7. ...
  8. Info := RttiContext.GetType(AnyClass);
  9. Meth := Info.GetMethod('AMethod');
  10. Setlength(Param,1);
  11. Param[0] := TValue.From<Integer>(11);
  12. Result := Meth.Invoke(ClassInstance,Param);
  13. ...
  14. end;

但是有了记录,这段代码不起作用,因为TRttiMethod类型不为记录类型提供Invoke()方法.我可以从记录类型访问Info.GetMethod(‘AMethod’)的方法信息.
例如,我有这样的记录:

  1. TRecordType = record
  2. Field1,Field2 : single;
  3. procedure Calc(Value : integer);
  4. end;

如果我有methodname或methodaddress,那么有没有人知道从记录中调用方法方法

解决方法

在探索上面评论中发布的delphi文档中的链接之后,我仔细研究了System.Rtti中的delphi类型TRttiRecordMethod.它提供了方法DispatchInvoke(),并且此方法需要一个指针.
以下代码有效:
  1. TRecordType = record
  2. Field1,Field2 : single;
  3. procedure Calc(Value : integer);
  4. end;
  5.  
  6.  
  7. Meth : TRttiMethod;
  8. Para : TRttiParameter;
  9. Param : TArray<TValue>;
  10. ARec : TRecordType;
  11. begin
  12. Info := RttiContext.GetType(TypeInfo(TRecordType));
  13. Meth := Info.GetMethod('Calc');
  14. Setlength(Param,1);
  15. Param[0] := TValue.From<Integer>(12);
  16. Meth.Invoke(TValue.From<Pointer>(@ARec),Param);
  17. end;

如果要调用静态方法或重载运算符,则代码不起作用. Delphi内部总是将自指针添加到参数列表,但这会导致访问.所以请使用此代码

  1. Meth : TRttiMethod;
  2. Para : TRttiParameter;
  3. Param : TArray<TValue>;
  4. ARec : TRecordType;
  5. begin
  6. Info := RttiContext.GetType(TypeInfo(TRecordType));
  7. Meth := Info.GetMethod('&op_Addition');
  8. ...
  9. Meth.Invoke(TValue.From<Pointer>(@ARec),Param);
  10. Result := System.Rtti.Invoke(Meth.CodeAddress,Param,Meth.CallingConvention,Meth.ReturnType.Handle,Meth.IsStatic);
  11. end;

猜你在找的Delphi相关文章