COM pass function pointer (delegate) as a method parameter to ActiveX object (implemented in C#)

做~自己de王妃 提交于 2019-12-11 04:53:22

问题


I'm working on a browser plugin using ActiveX/COM and I'm trying to pass a Javascript function to a method call so that it can be used as a callback. I've been able to get the function assigned to a property on the ActiveX object, but since the method is async all calls to the method must share the same callback.

I've seen this existing SO question but I'm not sure if this is the exact same problem since I'm not dealing directly with function pointers.

Example of what we have now:

var obj = new MyComObject();
obj.Callback = function(id) { Console.log(id); }
obj.DoMethodCallAsync("someId");
obj.DoMethodCallAsync("someOtherId");  // Uses the same callback.

Example of desired API:

var obj = new MyComObject();
obj.DoMethodCallAsync("someId", function(id) { Console.log("The first ID: " + id); }
obj.DoMethodCallAsync("someOtherId", function(id) { Console.log("The second ID: " + id); }

回答1:


Assuming the ActiveX is coded in C++, a JavaScript function object would be passed to an ActiveX method as IDispatch interface pointer. To call back this JavaScript function, you'd need to hold on to that interference and call IDispatch::Invoke(DISPID_VALUE, ...) when the job is done. All params passed to Invoke will be passed to the JavaScript function.

EDITED: If the control is in C#, a JavaScript function would be passed as an object to a C# method. It can be called back this way:

callback.GetType().InvokeMember("[DispID=0]",
  BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
  null, callback, new object[] { });

AFAIR, the member name can also be blank:

callback.GetType().InvokeMember(String.Empty,
  BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
  null, callback, new object[] { });


来源:https://stackoverflow.com/questions/18132783/com-pass-function-pointer-delegate-as-a-method-parameter-to-activex-object-im

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!