2012-04-17 62 views
7

我为我的应用程序编写了一个脚本语言,我的目标是使在脚本中发布任何类型的delphi成为可能。我使用rtti来自动完成这项任务。对于像类的任何实例类型,我使用以下代码从脚本中查找和调​​用方法。德尔福 - 每个名称的调用记录方法

var Info : TRttiType; 
    Meth : TRttiMethod; 
    Param : TArray<TValue>; 
    Result : TValue; 
    AnyClass : TClass; 
begin 
    ... 
    Info := RttiContext.GetType(AnyClass); 
    Meth := Info.GetMethod('AMethod'); 
    Setlength(Param, 1); 
    Param[0] := TValue.From<Integer>(11); 
    Result := Meth.Invoke(ClassInstance, Param); 
    ... 
end; 

但随着创纪录的代码不起作用,因为TRttiMethod型不提供记录类型的invoke()方法。我可以通过Info.GetMethod('AMethod')从记录类型访问方法信息。
例如,我有这样的记载:

TRecordType = record 
    Field1, Field2 : single; 
    procedure Calc(Value : integer); 
end; 

因此,没有人知道一种从记录调用一个方法,如果我有方法名或methodaddress?

+0

您刚刚重新创建[DWScript](http://code.google.com/p/dwscript/)吗? – 2012-04-17 13:55:26

+0

感谢您的提示,但我知道DWScript。我的语言是作为一个delphi程序的脚本接口,其结构像AObject.AFunction.AObject.DoSomething是可能的。 – DragonFlyOfGold 2012-04-17 14:05:19

+2

我认为DWScript可以做到这一切,但也许我错了 – 2012-04-17 14:15:19

回答

12

在浏览上面评论中发布的delphi文档中的链接后,我仔细查看了System.Rtti中的delphi类型TRttiRecordMethod。它提供DispatchInvoke()方法,并且此方法需要一个指针。 所以,下面的代码工作:

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; 

如果你想调用静态方法或重载运算符的代码不起作用。 Delphi内部始终将自指针添加到参数列表,但这会导致访问违规。因此,请改用此代码:

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

谢谢,这真的帮助我寻求一种动态调用SOAP Web服务的方法! – dahook 2012-06-28 22:57:10