简体   繁体   English

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

[英]Passing struct data type to named pipes in C++

I found one sample program that passes string from client to server in named pipes. 我找到了一个示例程序,该程序在命名管道中将字符串从客户端传递到服务器。 How can I pass a struct data type through named pipes in c++? 如何在C ++中通过命名管道传递struct数据类型?

WriteFile function of client looks like this: 客户端的WriteFile函数如下所示:

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

ReadFile function of server looks like this: 服务器的ReadFile函数如下所示:

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

The structure I need to pass looks like this: 我需要传递的结构如下所示:

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

In CreateNamedPipe() I'm using PIPE_TYPE_BYTE PIPE_READMODE_BYTE pipe mode. CreateNamedPipe()我使用PIPE_TYPE_BYTE PIPE_READMODE_BYTE管道模式。 Do I need to change them to PIPE_TYPE_BYTE and PIPE_READMODE_MESSAGE ? 我需要将它们更改为PIPE_TYPE_BYTEPIPE_READMODE_MESSAGE吗?

You cannot pass instances of a class across the wire. 您不能跨线传递类的实例。

You basically have two options. 您基本上有两个选择。

A) Use fixed size buffers: A)使用固定大小的缓冲区:

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

and just send sizeof(mydata) across the pipe. 并通过管道发送sizeof(mydata)

B) Marshal the data in a different format: B)以其他格式封送数据:

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

Here you basically have a fixed header portion with all the strings stored as bytes at the end. 在这里,您基本上有一个固定的标头部分,所有字符串都以字节结尾存储。 You find the start of a string by accessing the buffer at the appropriate offset. 您可以通过以适当的偏移量访问缓冲区来找到字符串的开头。 You need marshalling code at each end of the pipe to convert to/from your EventLogEntry and mywiredata structs. 您需要在管道的每一端进行编组代码以与EventLogEntrymywiredata结构进行相互转换。

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

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