Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling C# COM object

Tags:

c#

com

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?

like image 839
David Avatar asked Jan 26 '26 20:01

David


2 Answers

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.

like image 158
Frederik Gheysels Avatar answered Jan 28 '26 10:01

Frederik Gheysels


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 
like image 21
wsw Avatar answered Jan 28 '26 12:01

wsw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!