通过管道在c ++和c#之间进行通信

我想通过管道将数据从ac#应用程序发送到c ++应用程序。 这就是我所做的:

这是c ++客户端:

#include "stdafx.h" #include  #include  int _tmain(int argc, _TCHAR* argv[]) { HANDLE hFile; BOOL flg; DWORD dwWrite; char szPipeUpdate[200]; hFile = CreateFile(L"\\\\.\\pipe\\BvrPipe", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); strcpy(szPipeUpdate,"Data from Named Pipe client for createnamedpipe"); if(hFile == INVALID_HANDLE_VALUE) { DWORD dw = GetLastError(); printf("CreateFile failed for Named Pipe client\n:" ); } else { flg = WriteFile(hFile, szPipeUpdate, strlen(szPipeUpdate), &dwWrite, NULL); if (FALSE == flg) { printf("WriteFile failed for Named Pipe client\n"); } else { printf("WriteFile succeeded for Named Pipe client\n"); } CloseHandle(hFile); } return 0; 

}

这里是c#服务器

 using System; using System.IO; using System.IO.Pipes; using System.Threading; namespace PipeApplication1{ class ProgramPipeTest { public void ThreadStartServer() { // Create a name pipe using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("\\\\.\\pipe\\BvrPipe")) { Console.WriteLine("[Server] Pipe created {0}", pipeStream.GetHashCode()); // Wait for a connection pipeStream.WaitForConnection(); Console.WriteLine("[Server] Pipe connection established"); using (StreamReader sr = new StreamReader(pipeStream)) { string temp; // We read a line from the pipe and print it together with the current time while ((temp = sr.ReadLine()) != null) { Console.WriteLine("{0}: {1}", DateTime.Now, temp); } } } Console.WriteLine("Connection lost"); } static void Main(string[] args) { ProgramPipeTest Server = new ProgramPipeTest(); Thread ServerThread = new Thread(Server.ThreadStartServer); ServerThread.Start(); } } 

}

当我启动服务器然后客户端的客户端GetLastErrror返回2(系统找不到指定的文件。)

对此有任何想法。 谢谢

猜测,我会说在服务器中创建管道时不需要“\。\ Pipe \”前缀。 调用我看过的NamedPipeServerStream构造函数的示例只是传入管道名称。 例如

 using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("BvrPipe")) 

您可以使用SysInternals进程资源管理器列出打开的管道及其名称。 这应该可以帮助您validation管道是否具有正确的名称。 有关详细信息,请参阅此问

请阅读此内容以了解管道的实施方式。 为什么不使用CreateNamedPipes API调用? 您将C ++端的文件句柄视为普通文件而不是管道。 因此,当C ++代码实际上正在尝试从文件中读取时,它正在查找管道时失败。