Team LiB
Previous Section Next Section

CCW: Consuming .NET Objects from COM Clients

A COM Callable Wrapper (CCW) is used to wrap .NET components so they can be used from existing COM objects. There are four general rules that you must follow when using this approach:

To consume a managed type from COM, first register the assembly's type library:

regasm /tlb:MyTlb.tlb MyApp.dll

Then install the assembly in the local directory of the client application or in the GAC:

gacutil --I MyApp.dll

The assembly must have a strong name generated with sn.exe.

If you do not wish to place the item in the GAC, you can use the /codebase switch of regasm to register the DLL location, as in the following example:

regasm /codebase C:\Cases\RemotingLifetime\Bin\Debug\MyApp.dll /tlb:MyApp.tlb

Next, import the type libraries in the new C++ application. You must import both mscorlib.tlb and your assembly .tlb file.

#import "mscorlib.tlb"
#import "..\LoanLib\LoanLib.tlb"

Finally, create the .NET object using normal COM creation means, such as CoCreateInstance.

The following example demonstrates consuming .NET objects from COM clients.

Code Example: Consuming .NET Objects from COM Clients
Start example

#include <objbase.h>
#include <iostream.h>
#include <windows.h>

#import "mscorlib.tlb"
#import "C:\Projects\COM Examples\NETTOCOM\bin\Debug\NETTOCOM.tlb" no_namespace
named_guids

using namespace NETTOCOM;

int main()
{
    CoInitialize(NULL);
    BSTR MyString = SysAllocString(L"Hello World");
    IMyInterface* pMy = NULL;

    HRESULT hr = CoCreateInstance(__uuidof(MyClass),NULL,
               CLSCTX_INPROC_SERVER,__uuidof(IMyInterface),
                 (void**)&pMy);

    if( SUCCEEDED(hr) )
    {
        pMy->PrintHelloWorld(MyString);
        pMy->Release();
    }
    CoUninitialize();
    return 0;
}
End example

Team LiB
Previous Section Next Section