【问题标题】:How to get details on procedure types in a record using rtti in Delphi如何在 Delphi 中使用 rtti 获取记录中过程类型的详细信息
【发布时间】:2020-10-25 23:18:16
【问题描述】:

给定一个包含过程类型作为字段的 Delphi 记录,例如:

TProcType1 = function (index : integer; value : double) : string;
TProcType2 = function (bValue : boolean; ptr : TPointer) : integer; 
TMyRecord = record
   proc1 : TProcType1;
   proc2 : TProcType2;
end

是否可以获得有关过程类型签名的详细信息?例如,proc1 被声明为具有两个参数的过程类型,整数和双精度,返回类型为字符串?

我可以在字段上使用 ToString 将过程类型字段转换为字符串并解析它以获取信息,例如,使用如下代码:

 context := TRttiContext.Create;
 rtype := context.GetType(TypeInfo(TMyRecord));
 fields := rtype.GetFields;
 for i := 0 to High(fields) do
     begin
     astr := fields[i].FieldType.ToString;
     // parse astr to get info on procedure type
     end

我想知道是否有任何方法可以使用 rtti 解构过程类型,而不必手动解析为 ToString?对于普通的方法字段,这是可能的。

我可以保证记录将只包含过程类型字段。使用 Delphi 10.4

【问题讨论】:

  • 为什么需要这样做?
  • 目前更多的是一种好奇心,但我正在探索创建一个可以导出自记录 C 兼容 API 的 Delphi 库的想法。该库导出两种方法,一种返回指向表示库中功能的方法指针记录的指针,另一种返回指向反射方法记录的指针。我脑海中的想法是,当加载时,反射 API 可用于在运行时自动构建 Python 或 GUI 界面。这是周日下午可以玩的东西。
  • 这是已经存在的技术。它被称为类型库。
  • 使用它有什么乐趣?今天是星期天的下午,难道就不能找点乐子吗?
  • 我的意思是,如果您希望制作一些广泛有用的东西,那么类型库将是您的最佳选择。如果您想尝试、学习并获得乐趣,那没有错。

标签: delphi rtti


【解决方案1】:

是的,这很简单:

var
  Context: TRttiContext;
  RType: TRttiType;
  Field: TRttiField;
  p: TRttiProcedureType;
  param: TRttiParameter;
begin
  Context := TRttiContext.Create;
  RType := Context.GetType(TypeInfo(TMyRecord));
  for Field in RType.GetFields do
  begin
    if Field.FieldType is TRttiProcedureType then
    begin
      p := TRttiProcedureType(Field.FieldType);
      Writeln(p.Name);
      Writeln('Parameter count: ', Length(p.GetParameters));
      for param in p.GetParameters do
      begin
        Writeln('Parameter name: ', param.Name);
        if Assigned(param.ParamType) then
          Writeln('Parameter type: ', param.ParamType.ToString);
      end;
      if Assigned(p.ReturnType) then
        Writeln('Result type: ', p.ReturnType.ToString);
      Writeln;
    end;
  end;
end;

输出:

TProcType1
Parameter count: 2
Parameter name: index
Parameter type: Integer
Parameter name: value
Parameter type: Double
Result type: string

TProcType2
Parameter count: 2
Parameter name: bValue
Parameter type: Boolean
Parameter name: ptr
Parameter type: Pointer
Result type: Integer

TRttiParameter 还有一个Flags 属性,它是一个set,它告诉你参数的类型(例如varconstout)。

TRttiProcedureType也可以告诉你程序的calling convention

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多