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

时间:2009-12-15 10:41:46

标签: c# c++ ipc

我想通过管道将数据从c#应用程序发送到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;

}

这里是c#server

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(系统找不到指定的文件。)

对此有任何想法。 感谢

2 个答案:

答案 0 :(得分:6)

猜测一下,我说你在服务器上创建管道时不需要“\。\ Pipe \”前缀。调用我看过的NamedPipeServerStream构造函数的examples只传入管道名称。 E.g。

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

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

答案 1 :(得分:-1)

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

相关问题