Mapping a C# Com Interop class to fixed COM GUIDS


When you create a C# class, you can make it available as a COM objectto code outside of the VS.NET framework. This is done through use ofthe utility REGASM. REGASM creates a COM Type Library that describesthe COM aspects of the class for use by both early binding in C++(through #import directives) and late binding systems (such as VB6,through project references), and registers the COM class in theRegistry under the HKLM\Software\CLSID hierarchy.

However, every time you rebuild your assemblyand run REGASM on it, you will get new GUIDs (Globally UniqueIdentifiers) assigned for the COM Class ID, Interface ID, and TypeLibrary ID, UNLESS you know how to assigned fixed GUIDs to these COMentities. Why does it matter if the GUIDs change? For one thing, unlessyou unregister the old assembly before you create the new one, old GUIDentries will be left lying around in the registry. For another thing,any application that you have already built against a previouslycreated type library generated by REGASM will be looking for out ofdate GUIDs in the registry, and will probably fail to load the properassembly at runtime.

The key to specifying fixed GUIDS in C# isthrough C# attributes. There are three places where you need to specifyan attribute to specify a different GUID: on the Interface definitionfor the exposed COM interface(s) for the class; on the class definitionitself (the so-called COM coclass) and the type library (the so-calledLIBID). You specify the following constructs for interface and coclassdefinitions:

 

using System.Runtime.InteropServices;

[GuidAttribute("interface-guid")]
public interface IMyCOMInterface
{

}

[GuidAttribute("clsid-guid")]
public class CMyCOMClass : IMyComInterface
{
public CMyCOMClass() {…} // need a public default constructor for COM

}

For the LIBID, go to the AssemblyInfo classand add the following attribute before or after any of the otherassembly attributes you find there:

      [assembly: GuidAttribute("libid-guid")]

Note that the three quoted GUIDs in the above GuidAttributes must be unique and must be of the form

"{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"

Note also that you need to reference theSystem.Runtime.InteropServices namespace in order to get the definitionfor GuidAttribute.

Related Articles :

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!