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

itc*_*chy 6 c# c++ ipc

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

这是c ++客户端:

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>


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;
Run Code Online (Sandbox Code Playgroud)

}

这里是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();

    }
}
Run Code Online (Sandbox Code Playgroud)

}

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

对此有任何想法.谢谢

And*_*son 6

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

using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("BvrPipe"))
Run Code Online (Sandbox Code Playgroud)

您可以使用SysInternals进程资源管理器列出打开的管道及其名称.这应该可以帮助您验证管道是否具有正确的名称.有关详情,请参阅问题.