I am doing a project in whi开发者_如何学Pythonch i am using VC++ and C# both. VC++ is for hardware interface (no other go, i must use VC++ only) and the application side i am using C# (micro soft visual studio 2008).
For both the programs to communicate to each other i am using named pipes (this is also must).
I am able to communicate between C# and VC++, but NOT VC++ to C#.
I have given the code below which i am using in C#.
using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("mytestpipe"))
{
pipeStream.WaitForConnection();
Console.WriteLine("[Server] Pipe connection established");
using (StreamReader sr = new StreamReader(pipeStream))
{
while ((temp = sr.ReadLine()) != null)
{
MessageBox.Show(temp));
}
}
}
The problem here is the sr.ReadLine()
. is not terminated at all. It should stop once it finds null, but the null value given by VC++ is not taken as NULL in C#.
Now how should i go about?
The NULL constant in C++ is actually just a zero. A plain zero of type "int", nothing special about it. So when you write NULL to the pipe, you're just transmitting a zero, that's all. And the C# side dutifully reads that zero as part of the string it's reading.
ReadLine() terminates in two cases:
1) After encountering a "new line" sequence (that is, 0x0D 0x0A).
2) When the underlying stream has ended (which for this case means, when the pipe has been closed)
In second case, it returns whatever it had a chance to read before the stream was closed, and any subsequent calls to ReadLine() will return null.
Therefore, in order to make ReadLine() return null, you have to close the pipe from VC++ side.
However, I guess this is not what you're trying to do. Therefore, my advice is to first develop and carefully specify the protocol that you're going to use for communication, and only then get to actually coding receiving and transmitting sides.
ReadLine will only return NULL when it reaches the end of file. Do you close the pipe on the client side after sending the data?
精彩评论