2010-09-09 20 views
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 

如何將上述轉換爲ATL的方式,以便在COM組件被銷燬時管道自動關閉?ATL在C++的windows中打開命名管道的方式是什麼?

+1

什麼時候COM組件被銷燬? – 2010-09-09 15:00:02

回答

6

我不得不猜測你指的是什麼COM組件,因爲你的帖子很模糊。但是我猜你已經編寫了一個包裝或以其他方式使用命名管道的COM組件,並且當這個COM組件被銷燬時,你希望它自動發佈(ala RAII)。

在這種情況下,你會把任何清理代碼組件的FinalRelease()方法,例如:

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

的一次性清理硬幣的另一面是一次性初始化代碼。如果你也想打開這個命名管道時,COM組件實例化 - 這你的標題所暗示的,但您的文章沒有說 - 那麼你會在你的對象的FinalConstruct()方法做到這一點:

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; 
} 
0
#include <atlbase.h> 
#include <atlfile.h> 

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

推測,m_file是你的類的成員變量。當你的類實例獲得它的最終版本(並隨後被銷燬)時,m_file的析構函數將關閉與該管道關聯的句柄。