Sunday, November 23, 2008

Client Connectivity


A client programmer takes four basic steps when using COM to communicate with a server. Of course, real-life clients do many more things,

but when you peel back the complexity, you'll always find these four steps at the core. In this section we will present COM at it's lowest level -

using simple C++ calls.

Here is a summary of the steps we are going to perform:

1. Initialize the COM subsystem and close it when finished.

2. Query COM for a specific interfaces on a server.

3. Execute methods on the interface.

4. Release the interface.

For the sake of this example, we will assume an extremely simple COM server. We'll assume the server has already been written and save its

description for the next tutorial.

The server has one interface called IBeep. That interface has just one method, called Beep. Beep takes one parameter: a duration. The goal in

this section is to write the simplest COM client possible to attach to the server and call the Beep method.

Following is the C++ code that implements these four steps. This is a real, working COM client application.


#include "..\BeepServer\BeepServer.h"

// GUIDS defined in the server

const IID IID_IBeepObj =

{0x89547ECD,0x36F1,0x11D2,

{0x85,0xDA,0xD7,0x43,0xB2,0x32,0x69,0x28}};

const CLSID CLSID_BeepObj =

{0x89547ECE,0x36F1,0x11D2,

{0x85,0xDA,0xD7,0x43,0xB2,0x32,0x69,0x28}};

int main(int argc, char* argv[])

{


HRESULT hr; // COM error code

IBeepObj *IBeep; // pointer to interface

hr = CoInitialize(0); // initialize COM

if (SUCCEEDED(hr)) // macro to check for success

{

hr = CoCreateInstance(

CLSID_BeepObj, // COM class id

NULL, // outer unknown

CLSCTX_INPROC_SERVER, // server INFO

IID_IBeepObj, // interface id

(void**)&IBeep ); // pointer to interface

if (SUCCEEDED(hr))

{

// call method

hr = IBeep->Beep(800);

// release interface

hr = IBeep->Release();

}

}

// close COM

CoUninitialize();

return 0;

}


The header "BeepServer.h" is created when we compile the server. BeepServer is the in-process COM server we are going to write in the next

section. Several header files are generated automatically by developer studio when compiling the server. This particular header file defines the

interface IBeepObj. Compilation of the server code also generates the GUIDs seen at the top of this program. We've just pasted them in here

from the server project.

Let's look at each of the 4 steps in detail.

0 comments:

Your Title