【问题标题】:How to get current method's name in Delphi 7?如何在 Delphi 7 中获取当前方法的名称?
【发布时间】:2010-11-21 00:53:23
【问题描述】:

有什么方法可以知道我目前正在使用的方法的名称吗?

这样:

procedure TMyObject.SomeMethod();
begin
  Writeln('my name is: ' + <hocus pocus>); 
end;

会产生这个输出:

my name is: SomeMethod

【问题讨论】:

    标签: delphi delphi-7


    【解决方案1】:

    JCL 是免费的,并且有相应的功能。这确实取决于堆栈跟踪的效果以及存在多少调试信息。

    JclDebug.pas

    function FileByLevel(const Level: Integer = 0): string;
    function ModuleByLevel(const Level: Integer = 0): string;
    function ProcByLevel(const Level: Integer = 0): string;
    function LineByLevel(const Level: Integer = 0): Integer;
    

    【讨论】:

    • 我会补充说,如果没有某种调试信息,这根本无法完成。
    【解决方案2】:

    另见our TSynMapFile class

    它能够加载.map 文件,并将其压缩成优化的二进制格式。它将比.map 本身小得多(例如,900 KB .map -> 70 KB .mab)。这个.mab 可以很容易地嵌入到exe 中。因此它比 JCL 或 MadExcept 使用的格式要小,也比 Delphi 在编译时嵌入的信息要小。

    你会这样使用它:

    Map := TSynMapFile.Create; // or specify an exe name
    try
      i := Map.FindSymbol(SymbolAddr);
      if i>=0 then 
        writeln(Map.Symbols[i].Name);
      // or for your point:
      writeln(Map.FindLocation(Addr)); // e.g. 'SynSelfTests.TestPeopleProc (784)'
    finally
      Map.Free;
    end;
    

    例如,这是我们的日志记录类中使用它的方式。

    procedure TSynLog.Log(Level: TSynLogInfo);
    var aCaller: PtrUInt;
    begin
      if (self<>nil) and (Level in fFamily.fLevel) then begin
        LogHeaderLock(Level);
        asm
          mov eax,[ebp+4]  // retrieve caller EIP from push ebp; mov ebp,esp
          sub eax,5        // ignore call TSynLog.Enter op codes
          mov aCaller,eax
        end;
        TSynMapFile.Log(fWriter,aCaller); // here it will call TSynMapFile for the current exe
        LogTrailerUnLock(Level);
      end;
    end;
    

    此方法能够检索调用者的地址,并记录其单元名称、方法名称和行号。

    注意/编辑:mORMot 日志单元的源代码是SynLog.pas。更新后的文档是reacheable at this URI

    【讨论】:

    • 您可以使用它来记录来自正常调试版本(或使用外部映射发布?)的调用堆栈,而无需添加例如 Jedi 调试代码?在某些特定情况下,拥有可以记录和报告调用位置的代码可能非常有用。
    • @DavidM 是的,你可以这样做。如果没有附加 .map/.mab,它将记录十六进制地址。然后,我们的 LogView 工具能够从与 .exe 匹配的现有 .map 文件中检索源代码行。但是当然,由于我们的 .mab 格式非常小,我看不出有什么理由不在编译时将其嵌入到 .exe 中。
    • @ArnaudBouchez 你能告诉我如何在编译时将它嵌入到 .exe 中吗?
    • @ArnaudBouchez 答案顶部的链接已损坏。对于遇到此帖子的其他人,相关单位似乎在这里:github.com/synopse/mORMot/blob/master/SynLog.pas
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 2011-01-04
    • 2010-09-19
    • 2015-02-22
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    相关资源
    最近更新 更多