Calling C# COM object

泪湿孤枕 提交于 2019-12-02 03:34:59

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.

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 

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!