Tuesday, 6 August 2013

Consume C++ COM EXE in C# and Invoke methods

The following steps will accomplish the requirement to consume old C++ COM component to consume in C# applications.
Step 1: First create a .net reference dll from the com exe file.
Open visual studio command prompt and run the following command to generate the dll.
tlbimp "c:\Path\xxx.tlb" /out:"c:\Path\xxx.dll"

Once the dll is generated, then add reference that dll to your C# project.

Step 2:
After referencing to invoke any method from the com exe, the following steps can be helpful.
//Get the GUID of com class
Guid clsid = new Guid("Com class GUID");
//Get the type of the com component
Type type = Type.GetTypeFromCLSID(clsid, true);
//Instantiate a new object
object instance = Activator.CreateInstance(type);
//Method name to invoke
string methodName = "MymehodName";
//execute method
type.InvokeMember(methodName, BindingFlags.InvokeMethod, null, instance, strArguments);

That's it :).