15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

706 ❘ ChaPTer 26 interOp<br />

}<br />

public:<br />

STDMETHOD(Greeting)(BSTR name, BSTR* message);<br />

};<br />

OBJECT_ENTRY_AUTO(__uuidof(COMDemo), CCOMDemo)<br />

code snippet COMServer/COMDemo.h<br />

With this class definition, you have to add the second interface, IMath, as well as the methods that are<br />

defined with the IMath interface:<br />

class ATL_NO_VTABLE CCOMDemo:<br />

public CComObjectRootEx,<br />

public CComCoClass,<br />

public IDispatchImpl<br />

public IDispatchImpl<br />

{<br />

public:<br />

CCOMDemo()<br />

{<br />

}<br />

DECLARE_REGISTRY_RESOURCEID(IDR_COMDEMO)<br />

BEGIN_COM_MAP(CCOMDemo)<br />

COM_INTERFACE_ENTRY(IWelcome)<br />

COM_INTERFACE_ENTRY(IMath)<br />

COM_INTERFACE_ENTRY2(IDispatch, IWelcome)<br />

END_COM_MAP()<br />

DECLARE_PROTECT_FINAL_CONSTRUCT()<br />

HRESULT FinalConstruct()<br />

{<br />

return S_OK;<br />

}<br />

void FinalRelease()<br />

{<br />

}<br />

public:<br />

STDMETHOD(Greeting)(BSTR name, BSTR* message);<br />

STDMETHOD(Add)(long val1, long val2, long* result);<br />

STDMETHOD(Sub)(long val1, long val2, long* result);<br />

};<br />

OBJECT_ENTRY_AUTO(__uuidof(COMDemo), CCOMDemo)<br />

Now, you can implement the three methods in the file COMDemo.cpp with the following code. The CComBSTR<br />

is an ATL class that makes it easier to deal with BSTRs. In the Greeting() method, only a welcome<br />

message is returned, which adds the name passed in the first argument to the message that is returned.<br />

The Add() method just does a simple addition of two values, <strong>and</strong> the Sub() method does a subtraction <strong>and</strong><br />

returns the result:<br />

STDMETHODIMP CCOMDemo::Greeting(BSTR name, BSTR* message)<br />

{<br />

CComBSTR tmp("Welcome, ");<br />

tmp.Append(name);<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!