15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Using a CoM Component from a .neT Client ❘ 707<br />

}<br />

*message = tmp;<br />

return S_OK;<br />

STDMETHODIMP CCOMDemo::Add(LONG val1, LONG val2, LONG* result)<br />

{<br />

*result = val1 + val2;<br />

return S_OK;<br />

}<br />

STDMETHODIMP CCOMDemo::Sub(LONG val1, LONG val2, LONG* result)<br />

{<br />

*result = val1 - val2;<br />

return S_OK;<br />

}<br />

code snippet COMServer/COMDemo.cpp<br />

Now, you can build the component. The build process also confi gures the component in the registry.<br />

Creating a runtime Callable Wrapper<br />

You can now use the COM component from within .<strong>NET</strong>. To make this possible, you must create a<br />

runtime callable wrapper (RCW). Using the RCW, the .<strong>NET</strong> client sees a .<strong>NET</strong> object instead of the COM<br />

component; there is no need to deal with the COM characteristics because this is done by the wrapper. An<br />

RCW hides the IUnknown <strong>and</strong> IDispatch interfaces (see Figure 26 - 9) <strong>and</strong> deals itself with the reference<br />

counts of the COM object.<br />

IUnknown<br />

IDispatch<br />

.<strong>NET</strong><br />

IMath<br />

RCW<br />

IWelcome<br />

COM<br />

Client<br />

IWelcome<br />

IMath<br />

Object<br />

figure 26-9<br />

The RCW can be created by using the comm<strong>and</strong> - line utility tlbimp or by using Visual Studio.<br />

Starting the comm<strong>and</strong><br />

tlbimp COMServer.dll /out:Interop.COMServer.dll<br />

creates the fi le Interop.COMServer.dll , which contains a .<strong>NET</strong> assembly with the wrapper class. In<br />

this generated assembly, you can fi nd the namespace COMWrapper with the class CCOMDemoClass <strong>and</strong> the<br />

interfaces CCOMDemo , IMath , <strong>and</strong> IWelcome . The name of the namespace can be changed by using options<br />

of the tlbimp utility. The option /namespace allows you to specify a different namespace, <strong>and</strong> with<br />

/asmversion you can defi ne the version number of the assembly.<br />

Another important option of this comm<strong>and</strong>-line utility is /keyfile, which is used for<br />

assigning a strong name to the generated assembly. Strong names are discussed in Chapter 18.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!