October 11, 2008

Exposing .NET assembly as a COM object.

Exposing .NET Assemblies as COM components. - Trouble is that he suggest placing the .NET component in the GAC. The problem with this is that the assembly and all its dependencies must then have a strong name! Better expose on deploying .NET Assemblies as COM components Sourcing .Net events for COM Sinks Really Raising Events Handled by a C++ COM Sink Sinking events from managed code in unmanaged C++ This is the simple method that avoids the use of the GAC. In the 'AssemblyInfo.cs' file add the following:
// Setting ComVisible to false makes the types in this assembly not visible 
// to COM components.  If you need to access a type in this assembly from 
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(true)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f23114e6-5754-4793-b2c2-8cbe299421ad")]
The .Net component should have the following form:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace TestNETComComponent
   // Declare the interface
   [ComVisible(true), Guid("23661D34-4D5E-42e7-9992-CA64923E2221")]
   // No IDIspatch, only the simplest IUknown derived COM interface
   public interface ISomeInterface
      int DoSomething();
      int DoSomethingElse(string arg);

   // Need a class to implement the interface 
   public class TestNETCom : ISomeInterface
      #region ISomeInterface Members

      public int  DoSomething()
         return 1;

      public int DoSomethingElse(string arg)
     Debug.WriteLine("TestNETCom.DoSomethingElse() - " + m_SomeString);
         return 1;

Use this command line to register the assembly with COM and create the type library: regasm.exe /codebase /tlb TestNETComponent.dll To unregister the assembly: regasm.exe /unregister TestNETComponent.dll

No comments: