VextoR
VextoR

Reputation: 5185

How to call methods from COM object (cannot cast System.__ComObject to my COM class)

I can create COM object locally

var infsrv = new InfoServ.TInfoServerClass(); //COM object
infsrv.RunBsScript(bssScriptName, strOfParam); //calling method

But I needed to create COM object on server, so code is:

var myGuid = new Guid("00C4261D-0B2B-4230-A2CA-A9F4F2A46452");
var myType = Type.GetTypeFromCLSID(myGuid, servername);
InfoServ.TInfoServerClass infsrv = (InfoServ.TInfoServerClass)Activator.CreateInstance(myType);
infsrv.RunBsScript(bssScriptName, strOfParam);

but now it says:

Unable to cast COM object of type 'System.__ComObject' to class type 'InfoServ.TInfoServerClass'. COM components that enter the CLR and do not support IProvideClassInfo or that do not have any interop assembly registered will be wrapped in the __ComObject type. Instances of this type cannot be cast to any other class; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.

what should I do?

Upvotes: 0

Views: 2511

Answers (2)

Andy Hopper
Andy Hopper

Reputation: 3678

You should be able to cast the instance created by the call to Activator.CreateInstance to an interface.

You should have an interface defined in the Interop assembly named InfoServ.TInfoServer (or ITInfoServer if the type library explicitly defined an interface for it), and if you cast the object returned by Activator.CreateInstance to that interface, you should see all of the methods/properties the CoClass (TInfoServerClass) exposes.

Upvotes: 1

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56747

Usually you use the "Add Reference" dialog to add a reference to a COM library. Then you can use the imported types like you would use any other class.

Upvotes: 0

Related Questions