你如何发送一个命名pipe道string从umnanaged托pipe代码空间?

我似乎有一个命名pipe道101的问题。 我有一个非常简单的设置来连接从C ++非托pipe应用程序发送到C#托pipe应用程序的单工命名pipe道。 pipe道连接,但我不能通过pipe道发送“消息”,除非我closures似乎冲洗缓冲区并传递消息的句柄。 这就像消息被阻止。 我已经尝试颠倒客户机/服务器的angular色,并调用它们与不同的国旗组合,没有任何运气。 我可以很容易地从C#托pipe到C ++非托pipe的另一个方向发送消息。 有没有人有任何见解。 任何人都可以成功地发送消息从C托pipe非C托pipe? 我可以find大量的内部amanged或非pipe理的pipe道的例子,但不能相互pipe理/从unamanged – 只是声称能够做到这一点。

在清单中,为了清楚起见,我省略了许多包装材料。 我认为相关的关键是pipe道连接/创build/读取和写入方法。 不要担心在这里阻塞/线程太多。

C#服务器端

// This runs in its own thread and so it is OK to block private void ConnectToClient() { // This server will listen to the sending client if (m_InPipeStream == null) { m_InPipeStream = new NamedPipeServerStream("TestPipe", PipeDirection.In, 1); } // Wait for client to connect to our server m_InPipeStream.WaitForConnection(); // Verify client is running if (!m_InPipeStream.IsConnected) { return; } // Start listening for messages on the client stream if (m_InPipeStream != null && m_InPipeStream.CanRead) { ReadThread = new Thread(new ParameterizedThreadStart(Read)); ReadThread.Start(m_InPipeStream); } } // This runs in its own thread and so it is OK to block private void Read(object serverObj) { NamedPipeServerStream pipeStream = (NamedPipeServerStream)serverObj; using (StreamReader sr = new StreamReader(pipeStream)) { while (true) { string buffer = "" ; try { // Blocks here until the handle is closed by the client-side!! buffer = sr.ReadLine(); // <<<<<<<<<<<<<< Sticks here } catch { // Read error break; } // Client has disconnected? if (buffer == null || buffer.Length == 0) break; // Fire message received event if message is non-empty if (MessageReceived != null && buffer != "") { MessageReceived(buffer); } } } } 

C ++客户端

  // Static - running in its own thread. DWORD CNamedPipe::ListenForServer(LPVOID arg) { // The calling app (this) is passed as the parameter CNamedPipe* app = (CNamedPipe*)arg; // Out-Pipe: connect as a client to a waiting server app->m_hOutPipeHandle = CreateFile("\\\\.\\pipe\\TestPipe", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // Could not create handle if (app->m_hInPipeHandle == NULL || app->m_hInPipeHandle == INVALID_HANDLE_VALUE) { return 1; } return 0; } // Sends a message to the server BOOL CNamedPipe::SendMessage(CString message) { DWORD dwSent; if (m_hOutPipeHandle == NULL || m_hOutPipeHandle == INVALID_HANDLE_VALUE) { return FALSE; } else { BOOL bOK = WriteFile(m_hOutPipeHandle, message, message.GetLength()+1, &dwSent, NULL); //FlushFileBuffers(m_hOutPipeHandle); // <<<<<<< Tried this return (!bOK || (message.GetLength()+1) != dwSent) ? FALSE : TRUE; } } // Somewhere in the Windows C++/MFC code... ... // This write is non-blocking. It just passes through having loaded the pipe. m_pNamedPipe->SendMessage("Hi de hi"); ... 

Solutions Collecting From Web of "你如何发送一个命名pipe道string从umnanaged托pipe代码空间?"