2

I'm working with the JEDI Code Library to host a CLR for using C# code in Delphi. Using the TJclClrHost this works pretty good, for the common cases. However, now I'm in the situation where I'd like to register to an event in C# code. There are multiple options for this, a few examples of the C#-Code:

public event Action MyEvent;
public event Action<Object> MyEventWithParam;
public event EventHandler MyEventWithHandler;
public event EventHandler<CustomArgs> MyEventWithCustomHandler;

In Delphi, I retrieve the MethodInfo for add_MyEvent.... Depending on the used event I have to pass a [mscorlib]System.Action or [mscorlib]System.EventHandler. The question is, how do I create a matching instance in Delphi? Both expected arguments are delegates, so there is no constructor I could call to get an instance.

var
  instance: OleVariant;
  handler: OleVariant;
  clrAssembly: TJclClrAssembly;
  clrType: _Type;
  clrMethod: _MethodInfo;
begin
  clrAssembly := ...;  // I already have the assembly
  clrType := clrAssembly.GetType_2('MyAssembly.MyType');
  clrMethod := clrType.GetMethod_6('add_MyEvent');

  handler := ???

  // instance contains the specific instance of MyClass I want to register the EventHandler on
  clrMethod.Invoke_3(instance, PSafeArray(VarArrayAsPSafeArray(VarArrayOf([handler]))))

While I found a lot of resources regarding passing callbacks from managed to unmanaged code (e.g. this answer describes the UnmanagedFunctionPointer-attribute, there is also this MSDN article describing GetDelegateForFunctionPointer), I wasn't really able to find something that helps in my case.

Florian Koch
  • 1,372
  • 1
  • 30
  • 49

0 Answers0