Logo 
Search:

.Net Framework FAQ

Submit Interview FAQ
Home » Interview FAQ » .Net FrameworkRSS Feeds

Can I use COM components from .NET programs?

  Shared By: Orville Rodriguez    Date: Sep 21    Category: .Net Framework    Views: 1717

Answer:

Yes. COM components are accessed from the .NET runtime via a Runtime Callable Wrapper (RCW). This wrapper turns the COM interfaces exposed by the COM component into .NET-compatible interfaces. For oleautomation interfaces, the RCW can be generated automatically from a type library. For non-oleautomation interfaces, it may be necessary to develop a custom RCW which manually maps the types exposed by the COM interface to .NET-compatible types.

Here's a simple example for those familiar with ATL. First, create an ATL component which implements the following IDL:

import "oaidl.idl";
import "ocidl.idl";

[
object,
uuid(EA013F93-487A-4403-86EC-FD9FEE5E6206),
helpstring("ICppName Interface"),
pointer_default(unique),
oleautomation
]

interface ICppName : IUnknown
{
[helpstring("method SetName")] HRESULT SetName([in] BSTR name);
[helpstring("method GetName")] HRESULT GetName([out,retval] BSTR *pName );
};

[
uuid(F5E4C61D-D93A-4295-A4B4-2453D4A4484D),
version(1.0),
helpstring("cppcomserver 1.0 Type Library")
]
library CPPCOMSERVERLib
{
importlib("stdole32.tlb");
importlib("stdole2.tlb");
[
uuid(600CE6D9-5ED7-4B4D-BB49-E8D5D5096F70),
helpstring("CppName Class")
]
coclass CppName
{
[default] interface ICppName;
};
};
When you've built the component, you should get a typelibrary. Run the TLBIMP utility on the typelibary, like this:

tlbimp cppcomserver.tlb
If successful, you will get a message like this:

Typelib imported successfully to CPPCOMSERVERLib.dll
You now need a .NET client - let's use C#. Create a .cs file containing the following code:

using System;
using CPPCOMSERVERLib;

public class MainApp
{
static public void Main()
{
CppName cppname = new CppName();
cppname.SetName( "bob" );
Console.WriteLine( "Name is " + cppname.GetName() );
}
}
Compile the C# code like this:

csc /r:cppcomserverlib.dll csharpcomclient.cs
Note that the compiler is being told to reference the DLL we previously generated from the typelibrary using TLBIMP. You should now be able to run csharpcomclient.exe, and get the following output on the console:

Name is bob

Share: 
 

Didn't find what you were looking for? Find more on Can I use COM components from .NET programs? Or get search suggestion and latest updates.


Your Comment
  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].


Tagged: