Search code examples
c#c++.netmultithreadingnamed-pipes

"Pipe is broken" C# .NET pipe with C++ backend (WINDOWS)


So I am currently doing some interesting work with pipes. I have a C++ injectable dll which I inject in a process to get info about and report back to my C# GUI. I am using pipes to communicate between the backend and the frontend. That works fine, but when I try to communicate to the C++ injectable I receive a "Pipe is broken." error.

In my c++ dll I have the following :

HANDLE Pipe = CreateNamedPipe("\\\\.\\pipe\\TestPipe",
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
999999,
999999,
NMPWAIT_USE_DEFAULT_WAIT,
NULL);

void PipeThread() 
{
    int numbuff;
    DWORD dwRead;

    while (Pipe != INVALID_HANDLE_VALUE)
    {
        if (ConnectNamedPipe(Pipe, NULL) != FALSE)
        {
            if (ReadFile(Pipe, (LPVOID)numbuff, sizeof(int), &dwRead, NULL) != FALSE)
            {
                std::stringstream o;
                o << numbuff << "\r\n";
                Output(o.str());
                char buff[numbuff];
                while (ReadFile(Pipe, buff, numbuff, &dwRead, NULL) != FALSE)
                {
                    Output(std::string(buff)+"\r\n");
                }
            }
        }
        DisconnectNamedPipe(Pipe); 
    }
}

^ I have confirmed that thread was running

In my C# GUI I have something like so:

private void button1_Click(object sender, EventArgs e)
    {
        if (!connected)
            return;
        using (var pipe = new NamedPipeClientStream(".", "TestPipe", PipeDirection.Out))
        {
            pipe.Connect();
            byte[] outBuffer = Encoding.ASCII.GetBytes(TextBox.Text);
            byte[] strSize = BitConverter.GetBytes(outBuffer.Length);
            pipe.Write(strSize, 0, strSize.Length);
            pipe.Write(outBuffer, 0, outBuffer.Length);
            pipe.Flush();
        }
    }

However when running I get a "Pipe is broken" error from .NET. Why is this happening?


Solution

  • Did you try using StreamWriter?

    private void button1_Click(object sender, EventArgs e) { if (!connected) return; using (var pipe = new NamedPipeClientStream(".", "TestPipe", PipeDirection.Out)) { using (var stream = new StreamWriter(pipe)) { pipe.Connect(); stream.Write(TextBox.Text); pipe.Flush(); } } }