Calling C# COM object

2020-04-16 02:20发布

问题:

Ok, I've created a c# dll, made all its interface and methods all ComVisible(true). Added it to the GAC using gacutil, then registered it using regasm and created a type library tlb file.

Now I have another c# project that I want to make calls to that com object, how can I do this? What would the code roughly look like to import the com object then use its calls?

回答1:

First of all, why do you want to call that C# Assembly (that you've made comvisible) in your other C# project via COM ? That is not necessary ...

Ontopic: If you've created a tlb file, then you shouldn't do anything special. You can just reference the 'runtime callable wrapper' of the c#assembly you've created.



回答2:

Step 1: Create a Runtime-Callable-Wrapper. There are two ways

Method 1: using TlbImp to Generate RCW

tlbimp <YourCOMSvr>.tlb /out:<YourCOMSvr>.dll

using this way is using the default .NET-Interop Marshalling, sometimes (Meaning when it does not work) you need to change the marshalling by perform the additional steps

ildasm <YourCOMSvr>.dll /out:<YourCOMSvr>.il
//Modify <YourCOMSvr>.il 
ilasm <YourCOMSvr>.il /dll

Method 2: Manually create a C++/Cli project serves as a wrapper for the COM server

Step 2: C# Code

Reference the RCW and use the following code to connect to the COM Server

Type yourComType= Type.GetTypeFromProgID(yourComSvrProgID, serverPcName);
var oInterface = (IYourCOMInterface)Activator.CreateInstance(yourComType);
//Then start using oInterface 


回答3:

The moment your C# component becomes a COM qualified component, it also starts behaving like a qualified ActiveX component.

So an easy way out to test the COM calls will be to write a simple HTML page with JavaScript code as given below:

Set MyCOMObj = Server.CreateObject("NAME_OF_COM_EXPOSED_CLASS"); 
MyCOMObj.My_COM_Method();

If you are able to invoke the methods like this without any errors, it means your COM calls are working perfect.

Thanks and Regards
Anugrah Atreya
http://explorecsharp.blogspot.com



标签: c# com