我正在使用 JEDI 代码库来托管 CLR,以便在 Delphi 中使用 C# 代码。对于常见情况,使用TJclClrHost
this 效果很好。但是,现在我想在 C# 代码中注册一个事件。有多种选择,C#-Code 的一些示例:
public event Action MyEvent;
public event Action<Object> MyEventWithParam;
public event EventHandler MyEventWithHandler;
public event EventHandler<CustomArgs> MyEventWithCustomHandler;
在 Delphi 中,我检索add_MyEvent...
. 根据使用的事件,我必须通过 a[mscorlib]System.Action
或[mscorlib]System.EventHandler
. 问题是,如何在 Delphi 中创建匹配实例?两个预期的参数都是委托,所以没有可以调用的构造函数来获取实例。
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]))))
虽然我发现了很多关于将回调从托管代码传递到非托管代码的资源(例如,这个答案描述了UnmanagedFunctionPointer
-attribute,还有这篇 MSDN 文章描述GetDelegateForFunctionPointer
),但我真的找不到对我的情况有帮助的东西。