我找到了一个示例程序,该程序在命名管道中将字符串从客户端传递到服务器。如何在C ++中通过命名管道传递struct数据类型?
客户端的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_BYTE
和PIPE_READMODE_MESSAGE
吗?
答案 0 :(得分:2)
您不能跨类传递类的实例。
您基本上有两个选择。
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
};
这里,您基本上有一个固定的标头部分,所有字符串都以字节结尾存储。您可以通过以适当的偏移量访问缓冲区来找到字符串的开头。您需要在管道的每一端都编组代码,以与EventLogEntry
和mywiredata
结构进行相互转换。