Delphi - Invoke Record method per name

后端 未结 1 944
有刺的猬
有刺的猬 2021-02-09 12:49

I wrote a scriptlanguage for my applications and my goal is to make it possible to publish any type from delphi in the script. I use rtti to automatize this task. For any instan

相关标签:
1条回答
  • 2021-02-09 12:56

    After exploring the links in delphi documentations posted in the comments above I took a closer look at the delphi type TRttiRecordMethod in System.Rtti. It provides the method DispatchInvoke() and this method expects a pointer. So following code works:

    TRecordType = record   
      Field1, Field2 : single;   
      procedure Calc(Value : integer);    
    end; 
    
    
      Meth : TRttiMethod; 
      Para : TRttiParameter; 
      Param : TArray<TValue>; 
      ARec : TRecordType; 
    begin 
      Info := RttiContext.GetType(TypeInfo(TRecordType)); 
      Meth := Info.GetMethod('Calc'); 
      Setlength(Param, 1); 
      Param[0] := TValue.From<Integer>(12); 
      Meth.Invoke(TValue.From<Pointer>(@ARec), Param); 
    end; 
    

    If you want to call a static method or overloaded operator the code doesn't work. Delphi internally always add the self pointer to parameterlist, but this will cause a accessviolation. So use this code instead:

      Meth : TRttiMethod; 
      Para : TRttiParameter; 
      Param : TArray<TValue>; 
      ARec : TRecordType; 
    begin 
      Info := RttiContext.GetType(TypeInfo(TRecordType)); 
      Meth := Info.GetMethod('&op_Addition'); 
      ... 
      Meth.Invoke(TValue.From<Pointer>(@ARec), Param); 
      Result := System.Rtti.Invoke(Meth.CodeAddress, Param, Meth.CallingConvention, Meth.ReturnType.Handle, Meth.IsStatic); 
    end;    
    
    0 讨论(0)
提交回复
热议问题