Home > Net >  Procedure of object how to change the _self?
Procedure of object how to change the _self?

Time:05-12

I have

Type
  TProcOfObject = Procedure of Object;

var 
  MyProc: TProcOfObject;

now if I do

MyProc := MyObject.MyProc

then when I will call MyProc self will be equal to MyObject (I do not yet fully understand where self is stored in MyProc). Is their a way to call myProc with another value than MyObject for Self ?

CodePudding user response:

I do not yet fully understand where self is stored in MyProc

A method pointer is represented by the TMethod record, which contains 2 pointers as members - Data points to the Self object, and Code points to the beginning of the method's code.

When a method pointer is invoked as a function at compile-time, the compiler outputs codegen which executes the Code passing in the Data as the Self parameter.

Is their a way to call myProc with another value than MyObject for Self ?

You can type-cast the method pointer to TMethod to access its inner pointers, eg:

var 
  MyProc: TProcOfObject;

...

TMethod(MyProc).Data := ...; // whatever value you want Self to be
TMethod(MyProc).Code := ...; // whatever function you want to call

...

MyProc();
  • Related