Communication between C ++ and C # through the channel

I want to send data from a C # application to a C ++ application through a pipe. Here is what I did:

this is a C ++ client:

#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; 

}

and here is the 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(); } } 

}

when I start the server and then the GetLastErrror client from the client returns 2 (the system cannot find the specified file.)

Any idea on this. Thanks

+6
c ++ c # ipc
source share
2 answers

Under the assumption, I would say that when creating a channel on the server, you do not need the prefix "\. \ Pipe". the examples of calling the NamedPipeServerStream constructor that I saw just pass the channel name. For example.

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

You can specify open channels and their names using SysInternals explorer. This should help you verify that the channel name is correct. See this for more details.

+6
source share

Read this to find out how pipes are implemented. Why aren't you using CreateNamedPipes API? You treat the file descriptor on the C ++ side as a regular file, not a pipe. Therefore, your C ++ code fails when it searches for a channel, when in fact it tried to read from a file.

-one
source share

All Articles