c++ - 将结构数据类型传递给 C++ 中的命名管道

标签 c++ winapi ipc named-pipes

我找到了一个示例程序,它通过命名管道将字符串从客户端传递到服务器。如何在 C++ 中通过命名管道传递结构数据类型?

客户端的 WriteFile 函数如下所示:

WriteFile(hPipe,TEXT("Hello Pipe\n"),12,&dwWritten,NULL);

服务器的ReadFile函数如下所示:

while (ReadFile(hPipe, buffer, sizeof(buffer)-1, &dwRead, NULL))

我需要传递的结构如下所示:

struct EventLogEntry 
   {
       string date;
       string time;
       string subsystem;
       unsigned long eventType;
       string majorFunction;
       string messageText;
       unsigned long timeStamp; //Added for TimeZone Corrections
   };

CreateNamedPipe() 中,我正在使用 PIPE_TYPE_BYTE PIPE_READMODE_BYTE 管道模式。我是否需要将它们更改为 PIPE_TYPE_BYTEPIPE_READMODE_MESSAGE

最佳答案

您不能通过线路传递类的实例。

你基本上有两个选择。

A) 使用固定大小的缓冲区:

struct mydata {
  char message[200];
  char name[50];
  int time;
};

然后通过管道发送 sizeof(mydata)

B) 以不同的格式编码数据:

struct mywiredata {
  int messageoffset;
  int nameoffset;
  int time;
  char buffer[ANYSIZE_ARRAY]; //blogs.msdn.microsoft.com/oldnewthing/20040826-00/?p=38043
};

这里基本上有一个固定的 header 部分,所有字符串都存储为末尾的字节。您可以通过在适当的偏移量处访问缓冲区来找到字符串的开头。您需要在管道的每一端编码代码以转换为您的 EventLogEntrymywiredata 结构。

关于c++ - 将结构数据类型传递给 C++ 中的命名管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51170607/

相关文章:

c - 为什么编译器会抛出这个警告 : "missing initializer"? Is the structure initialized?

.net - 从 Perl 调用 .NET

c++ - 在 C++ 上(在 ubuntu 上)我必须为编译器配置什么才能找到导入?(如 iostream、stdio、math 等)

c++ - 如何在 Windows 内核模式下获取进程使用的 CPU 时钟周期?

c++ - 通用统一初始化 : `double` to `int`

c++ - 我的循环不想结束

c - 如何释放 BITMAP 结构?

winapi - 如何在管道上使用 WriteFile 修复乱码?

sockets - 哪些进程间通信方法适用于终端服务器?

.net-2.0 - 当消息变大时,IpcChannel Remoting变慢