tags:

views:

68

answers:

2
hPipe = CreateFile( 
         lpszPipename,   // pipe name 
         GENERIC_READ |  // read and write access 
         GENERIC_WRITE, 
         0,              // no sharing 
         NULL,           // default security attributes
         OPEN_EXISTING,  // opens existing pipe 
         0,              // default attributes 
         NULL);          // no template file 

How to convert the above to ATL way so that the pipe is automatically closed when the COM component is destroyed?

+6  A: 

I have to guess what COM component you are referring to, since your post was vague. But I'm guessing you have written a COM component that wraps or otherwise uses a named pipe, and you want it to be automatically released (ala RAII) when this COM component is destroyed.

In this case, you would put any cleanup code in the component's FinalRelease() method, for example:

void CoMyObject::FinalRelease()
{
  CloseHandle(my_pipe_handle_);
}

The other side of the one-time-cleanup coin is one-time-initialization code. If you also want to open this named pipe when the COM component is instantiated -- which your title suggests but your post doesn't say -- then you would do this in your object's FinalConstruct() method:

HRESULT CoMyObject::FinalConstruct()
{
  my_pipe_handle_ = CreateFile( 
         lpszPipename,   // pipe name 
         GENERIC_READ |  // read and write access 
         GENERIC_WRITE, 
         0,              // no sharing 
         NULL,           // default security attributes
         OPEN_EXISTING,  // opens existing pipe 
         0,              // default attributes 
         NULL);          // no template file }

  return S_OK;
}
John Dibling
A: 
#include <atlbase.h>
#include <atlfile.h>

CAtlFile m_file;
m_file.Create(lpszPipeName, GENERIC_READ|GENERIC_WRITE, 0, OPEN_EXISTING);

Presumably, m_file is a member variable of your class. When your class instance gets its final release (and subsequently destroyed), the destructor of m_file will close the handle associated with the pipe.

selbie