Logo 
Search:

.Net Framework FAQ

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

Can I use .NET components from COM programs?

  Shared By: Bonifaco Garcia    Date: Dec 15    Category: .Net Framework    Views: 1964

Answer:

Yes. .NET components are accessed from COM via a COM Callable Wrapper (CCW). This is similar to a RCW (see previous question), but works in the opposite direction. Again, if the wrapper cannot be automatically generated by the .NET development tools, or if the automatic behaviour is not desirable, a custom CCW can be developed. Also, for COM to 'see' the .NET component, the .NET component must be registered in the registry.

Here's a simple example. Create a C# file called testcomserver.cs and put the following in it:

using System;
using System.Runtime.InteropServices;

namespace AndyMc
{
[ClassInterface(ClassInterfaceType.AutoDual)]
public class CSharpCOMServer
{
public CSharpCOMServer() {}
public void SetName( string name ) { m_name = name; }
public string GetName() { return m_name; }
private string m_name;
}
}
Then compile the .cs file as follows:

csc /target:library testcomserver.cs
You should get a dll, which you register like this:

regasm testcomserver.dll /tlb:testcomserver.tlb /codebase
Now you need to create a client to test your .NET COM component. VBScript will do - put the following in a file called comclient.vbs:

Dim dotNetObj
Set dotNetObj = CreateObject("AndyMc.CSharpCOMServer")
dotNetObj.SetName ("bob")
MsgBox "Name is " & dotNetObj.GetName()
and run the script like this:

wscript comclient.vbs
And hey presto you should get a message box displayed with the text "Name is bob".

An alternative to the approach above it to use the dm.net moniker developed by Jason Whittington and Don Box.

Share: 
 

Didn't find what you were looking for? Find more on Can I use .NET components from COM 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: