简体   繁体   English

用C ++在Windows中打开命名管道的ATL方法是什么?

[英]What's the ATL way to open a named pipe in windows in c++?

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? 如何将以上转换为ATL方式,以便在销毁COM组件时自动关闭管道?

I have to guess what COM component you are referring to, since your post was vague. 由于您的帖子含糊不清,我不得不猜测您指的是什么COM组件。 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. 但是我想您已经编写了一个包装或使用命名管道的COM组件,并且您希望在销毁该COM组件时将其自动释放(ala RAII )。

In this case, you would put any cleanup code in the component's FinalRelease() method, for example: 在这种情况下,您可以将任何清除代码放入组件的FinalRelease()方法中,例如:

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: 如果您还想在实例化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;
}
#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. 大概m_file是您的类的成员变量。 When your class instance gets its final release (and subsequently destroyed), the destructor of m_file will close the handle associated with the pipe. 当您的类实例获得最终发布(并随后销毁)时,m_file的析构函数将关闭与管道关联的句柄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM