I've found the answer but negative to what I'm trying to do:
Passing method pointer from C# to Delphi DLL
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 "Attempted to read or write protected memory".
Delphi 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;
and C# 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);
The similar question I believe is, but didn't get an answer: