Consider this typical code for method tracing (simplified for illustration):
type
IMethodTracer = interface
end;
TMethodTracer = class(TInterfacedObject, IMethodTracer)
private
FName: String;
FResultAddr: Pointer;
FResultType: PTypeInfo;
public
constructor Create(
const AName: String;
const AResultAddr: Pointer = nil;
const AResultType: PTypeInfo = nil);
destructor Destroy; override;
end;
constructor TMethodTracer.Create(
const AName: String;
const AResultAddr: Pointer;
const AResultType: PTypeInfo);
begin
inherited Create();
FName := AName;
FResultAddr := AResultAddr;
FResultType := AResultType;
Writeln('Entering ' + FName);
end;
destructor TMethodTracer.Destroy;
var
lSuffix: String;
lResVal: TValue;
begin
lSuffix := '';
if FResultAddr <> nil then
begin
//there's probably a more straight-forward to doing this, without involving TValue:
TValue.Make(FResultAddr, FResultType, lResVal);
lSuffix := ' - Result = ' + lResVal.AsString;
end;
Writeln('Leaving ' + FName + lSuffix);
inherited Destroy;
end;
function TraceMethod(
const AName: String;
const AResultAddr: Pointer;
const AResultType: PTypeInfo): IMethodTracer;
begin
Result := TMethodTracer.Create(AName, AResultAddr, AResultType);
end;
//////
function F1: String;
begin
TraceMethod('F1', @Result, TypeInfo(String));
Writeln('Doing some stuff...');
Result := 'Booyah!';
end;
F1();
This is working as intended. The output is:
Entering F1
Doing some stuff...
Leaving F1 - Result = Booyah!
I am now looking for a way to minimize the number of required parameters for the call to TraceMethod()
, ideally allowing me to skip the Result
-related arguments altogether. I have no experience with assembler or stack layout myself but If I am not mistaken, judging by the "magic" I have seen other people do, at least the memory address of the implied magic Result
-variable should be obtainable somehow, shouldn't it? And possibly one can work from there to get at its type info, too?
Of course, if it were possible to even determine the name of the "surrounding" function itself that would eliminate the need for passing arguments to TraceMethod
entirely...
I am using Delphi XE2, so all recently introduced language/framework features can be used.
And before anyone mentions it: My actual code already uses CodeSite.EnterMethod
/ExitMethod
instead of Writeln
-calls. I am also aware that this simplified example cannot handle complex types and performs no error handling whatsoever.