如何在Delphi 7中获取当前方法的名称?

tom*_*azy 24 delphi delphi-7

有没有办法知道我目前所处方法的名称?

以便:

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

会产生这个输出:

my name is: SomeMethod

Lar*_*ens 27

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;
Run Code Online (Sandbox Code Playgroud)

  • 如果没有某种调试信息,我会添加这个简单的功能. (14认同)

Arn*_*hez 7

另见我们的TSynMapFile课程.

它能够加载.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;
Run Code Online (Sandbox Code Playgroud)

例如,以下是我们的日志记录类的使用方法.

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;
Run Code Online (Sandbox Code Playgroud)

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