开发者

Instantiating a legacy COM object in C# dynamically (using its ID in a string)

开发者 https://www.devze.com 2023-04-03 02:23 出处:网络
In Python, when I want to use this COM object, all I do is win32com.client.Dispatch(\"Myapp.Thing.1\") and it gives me an object which I can call methods and such on.

In Python, when I want to use this COM object, all I do is win32com.client.Dispatch("Myapp.Thing.1") and it gives me an object which I can call methods and such on.

I want to do this in C# and, shockingly, I can't seem to figure out how. I do not want to use one of those automatically generated COM wrappers, for reasons I can't get into. I need to do the late binding, dynamic COM of times past.

I've tried doing this, but I get a Null Ref Exception on the invoke call.

Type t = Type.GetTypeFromProgID("Myapp.Thing.1")
o = Activator.CreateInstance(t) 
t.GetMethod("xyz").Invoke(o, args) 

Any example code that is able to load up a COM object b开发者_JAVA技巧y its name and use it in some basic manner would be ideal.


When your type is retrieved via GetTypeFromProgID, You don't actually have the type - you have a __ComObject type which wraps the COM object created - so it doesn't have method "xyz" on it. Hence your null reference exception - GetMethod("xyx") is returning null.

In order to invoke the method, use t.InvokeMember("xyz", BindingFlags.InvokeMethod, null, o, args) instead:

Type t = Type.GetTypeFromProgID("Myapp.Thing.1")
o = Activator.CreateInstance(t) 
t.InvokeMember("xyz", BindingFlags.InvokeMethod, null, o, args)


You should to use the dynamic type it's exactly what it's for. You wont be able to type the instance without the wrappers. Instead you can do this.

 dynamic app = Activator.CreateInstance(
                                       Type.GetTypeFromProgID("MyApp.Thing.1"));
 app.XYZ():
0

精彩评论

暂无评论...
验证码 换一张
取 消