title: Marshaling C# caller for Delphi procedure of object
body: <p>I've found the answer but negative to what I'm trying to do:</p>
  <p><a href="https://stackoverflow.com/questions/4153549/passing-method-pointer-from-c-sharp-to-delphi-dll">Passing method pointer from C# to Delphi DLL</a></p>
  <p>Is there a possibility of call a delegate of object from Delphi in C#? Because all of Delphi callers from the example above are static and exported. I am using OleVariant and would like to invoke a caller from Delphi object in C# using GetDelegateForFunctionPointer. But when I try, debugger in Delphi event break in that method and then I get &quot;Attempted to read or write protected memory&quot;.</p>
  <p>Delphi code:</p>
  <pre><code>TOnEvent = procedure() of object;
  TOnEventStdCall = procedure() of object; stdcall;
  
  TSimpleClass = class
    FUserControl: OleVariant;
    FOnEventHandler : TOnEvent;
    FOnEventStdCallHandler : TOnEventStdCall;
    constructor Create();  
    procedure ProcOnEventStdCall(); stdcall;
  end;    
  ...
  constructor TSimpleClass.Create();
  begin
    FHost := TJclClrHost.Create('v4.0.30319');
    FHost.Start;
    FUserControl := FHost.DefaultAppDomain.CreateInstance('CSharpLibrary','CSharpLibrary.Init').Unwrap;
    FOnEventHandler := nil;
    FOnEventStdCallHandler := ProcOnEventStdCall;
    FUserControl.SetEvent(LongInt(@FOnEventStdCallHandler), LongInt(self));
  end;
  
  procedure TSimpleClass.ProcOnEventStdCall; stdcall;
  begin
      ShowMessage('Invoked');
      if Assigned(FOnEventHandler) then 
        FOnEventHandler();               // !!! exception here
  end;
  </code></pre>
  <p>and C# code:</p>
  <pre><code> struct TMethod
   {
      IntPtr pMethod;
      IntPtr pInstance;  
   }
   [UnmanagedFunctionPointer(CallingConvention.StdCall)]
   public delegate void TEvent(IntPtr instance);
   private TOnEventStdCall _delphiHandler;
  
   public void SetEvent(Int32 method, Int32 instance)
   {
        m.pMethod = new IntPtr(method);
        m.pInstance = new IntPtr(instance);
        _delphiHandler += (TEvent)Marshal.GetDelegateForFunctionPointer(m.pMethod, typeof(TEvent));
   }
  ...
  _delphiHandler.Invoke(m.pInstance);
  </code></pre>
  <p>The similar question I believe is, but didn't get an answer:</p>
  <p><a href="https://stackoverflow.com/questions/43119542/c-sharp-equivalent-of-pascal-delphi-procedure-of-object">c# equivalent of pascal/delphi procedure of object</a></p>