Weird result in ReadFile for named pipe

I had been trying to pass a struct between processes via named pipe (using IO overlap. This struct is simply a string plus a double. It was working ok when I put in a short string, but when I put a longer one (16 char to be precise) it fails to read it properly in ReadFile. Here is my code

The structure that is to be passed:
1
2
3
4
struct TestObj {
	std::string name;
	double value;
};


Server code:
1
2
3
4
5
6
7
8
9
10
11
TestObj objOut;
objOut.name = input;
objOut.value = -1.;

lpPipeInst[i]->cbToWrite = sizeof(TestObj);
BOOL fSuccess = WriteFileEx(
	lpPipeInst[i]->hPipeInst,
	&objOut,
	lpPipeInst[i]->cbToWrite,
	(LPOVERLAPPED)lpPipeInst[i],
	NULL);


Client code:
1
2
3
4
5
6
7
TestObj testObj;
fSuccess = ReadFile(
	hClient,    // pipe handle 
	&testObj,    // buffer to receive reply 
	sizeof(TestObj),  // size of buffer 
	&cbRead,  // number of bytes read 
	NULL);    // not overlapped  


Note that sizeof(TestObj) returns 40. When I put in shorter string for 'name' it was ok. Beyond 16 characters it fails. In debug mode it says the 'name' field as "<Error reading characters of string.>" and when I click on its individual char it says "<Unable to read memory>" with size = 16 and capacity = 31. When it was ok (say I pass in string with 15 characters) size = capacity = 15. Note that both cbToWrite and cbRead = 40 in all cases.

Can anyone help?
You can't just read/write the TestObj structure as a simple block of consecutive bytes, because it contains the complex class std::string which does its own memory management. Perhaps the simplest solution (though may not suit your requirements) is to change the struct to use only primitive types, in this case a c-string (array of characters) rather than std::string.
thanks that works great
Topic archived. No new replies allowed.