Search code examples
delphiassemblydelphi-2010basm

Call Object Method using ASM


To better explain what I'm trying to accomplish, I'm going to start with something that works.

Say we have a procedure that can call another procedure and pass a string parameter to it:

procedure CallSaySomething(AProc: Pointer; const AValue: string);
var
  LAddr: Integer;
begin
  LAddr := Integer(PChar(AValue));
  asm
    MOV EAX, LAddr
    CALL AProc;
  end;
end;

This is the procedure that we will call:

procedure SaySomething(const AValue: string);
begin
  ShowMessage( AValue );
end;

Now I can call SaySomething like so(tested and works (: ):

CallSaySomething(@SaySomething, 'Morning people!');

My question is, how can I achieve similar functionality, but this time SaySomething should be a method:

type
  TMyObj = class
  public
    procedure SaySomething(const AValue: string); // calls show message by passing AValue
  end;

so, if you're still with me..., my goal is to get to a procedure similar to:

procedure CallMyObj(AObjInstance, AObjMethod: Pointer; const AValue: string);
begin
  asm
    // here is where I need help...
  end;
end;

I've gave it quite a few shots, but my assembly knowledge is limited.


Solution

  • what is the reason to use asm?

    when you are calling objects method, then instance pointer have to be the first parameter in method call

    program Project1;
    {$APPTYPE CONSOLE}
    {$R *.res}
    
    uses System.SysUtils;
    type
        TTest = class
            procedure test(x : integer);
        end;
    
    procedure TTest.test(x: integer);
    begin
        writeln(x);
    end;
    
    procedure CallObjMethod(data, code : pointer; value : integer);
    begin
        asm
            mov eax, data;
            mov edx, value;
            call code;
        end;
    end;
    
    var t : TTest;
    
    begin
        t := TTest.Create();
        try
            CallObjMethod(t, @TTest.test, 2);
        except
        end;
        readln;
    end.