Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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 by its name and use it in some basic manner would be ideal.

like image 815
William Avatar asked Sep 07 '11 18:09

William


2 Answers

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)
like image 103
Philip Rieck Avatar answered Oct 17 '22 23:10

Philip Rieck


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():
like image 10
TheCodeKing Avatar answered Oct 17 '22 23:10

TheCodeKing