title: Pascal Overriding class methods during runtime
body: <p>I am trying to overwrite an object method during runtime.<br>
  I managed to get the addr of the method and I can be sure it is corrct (see read-only usage).<br>
  My problem is that I can <strong>only</strong> get read-only access to methods code address<br></p>
  
  <p>Therefor I either need a way: <br>
   - to force write into a Ram-Area that is protected<br>
   - to copy the whole class type into a non-protected area and modify it there. (this would be even more useful, because I would still have the original version to hand)</p>
  
  <pre><code>program DynClass;
  
  uses
   System.SysUtils,
   System.Rtti,
   System.TypInfo;
  
  type
   TObjectMethod = procedure of Object;
   TObjectTest = class(TObject)
   public
    fieldVar: integer;
    procedure ov1; virtual; // &lt;-- virtual does not help
    procedure ov2; virtual; // &lt;-- the method I an trying to override
  end;
  { TObjectTest }
  procedure TObjectTest.ov1; begin writeLn('TObjectTest.ov1'); end;
  procedure TObjectTest.ov2; begin writeLn('TObjectTest.opasv2'); end;
  
  // the Method thats supposed to replace it
  procedure Override_ov1(self: TObject);
  begin writeLn('TOverrideSrc.ov1'); writeLn(TObjectTest(self).fieldVar); end;
  
  var obj: TObjectTest;
  var fMethod: TMethod;
  var C: TRttiContext;
  var T: TRttiType;
  var M: TRttiMethod;
  var VTMEntry: PVmtMethodEntry;
  begin try
    obj := TObjectTest.Create;
    obj.fieldVar := 21;
  
    T := C.GetType(TypeInfo(TObjectTest));
    M := T.GetMethod('ov2');
    VTMEntry := PVmtMethodExEntry(m.Handle).Entry;
    writeln('address(API):       0x',IntToHex(Integer(M.CodeAddress),8));
    writeln('address(Container): 0x',IntToHex(Integer(VTMEntry^.CodeAddress),8));
    // ^ note: The address in the container matches the address the Rtti API offers
    //     --&gt; I really have the virtual method table entry
  
    // vvv This both works (meaning that all addresses are correct)
    fMethod.Data := obj;
    fMethod.Code := VTMEntry^.CodeAddress;
    TObjectMethod(fMethod)(); // call the method in the VTMEntry
    fMethod.Code := addr(Override_ov1);
    TObjectMethod(fMethod)(); // call the method I want to use in overriding
    // ^^^
  
    VTMEntry^.CodeAddress := addr(Override_ov1);
    // ^ access violation here
    obj.ov2; // if all works, this should do the same as the call above
   except on E: Exception do begin
    writeLn(E.ClassName+':'+E.Message);
   end; end;
   readLn;
  
  end.
  </code></pre>