简体   繁体   中英

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

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); }

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[] { });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM