Geeks With Blogs
Tex-blog Mobile and other stuff
Short sample for chapter 13, lesson 2. It shows how to write C# class library and export it to COM dll, which later is used by C++ test project. All is compiled from command line, so use Visual Studio 2005 Command Prompt.

// This is the contents of LibClass1.cs, a library we want to expose to COM

using System;
namespace ClassLibrary
{
  public interface ITestClass {
     void TestCallMe();
  }
  public class TestClass : ITestClass
  {
    public void TestCallMe()
    {
      Console.WriteLine("I was called!");
    }
  }
}

// This the contents of ComTester.cpp, this is where we want to use above class library

#include <atlbase.h>
#include <atlstr.h>
#import "LibClass1.tlb" raw_interfaces_only, named_guids
int _tmain(int argc, _TCHAR* argv[]) {
  HRESULT hr = CoInitialize(NULL);
  LibClass1::ITestClassPtr class1(LibClass1::CLSID_TestClass);
  class1->TestCallMe();
  CoUninitialize();
    return 0;
}

put both of those files in single directory, and execute following commands:

rem Create strong named key file
sn.exe -k key.snk

rem Compile library
csc /t:library /keyfile:key.snk LibClass1.cs

rem Create type library and register it in registry
regasm LibClass1.dll /tlb:LibClass1.tlb

rem Copy assembly to GAC
gacutil /i LibClass1.dll

rem Compile test C++ application
cl ComTester.cpp

rem Execute program, it should show "I was called!"
ComTester.exe

Some usefull references:
http://www.codeproject.com/dotnet/nettocom.asp
"COM Interop Sample: COM Client and Windows Server 2003" on MSDN

Also, it is always easier to just check "Register for COM interop" on Build tab in project properties, and VS will generate .dll with .tlb for you. Posted on Thursday, October 18, 2007 7:20 PM 70-536 preparation | Back to top


Comments on this post: Exposing .NET Component to COM (Ch13)

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Martinez | Powered by: GeeksWithBlogs.net