I have an API for a game, which calls methods in a C++ dll, you can write bots for the game by modifying the DLL and calling certain methods. This is fine, except I’m not a big fan of C++, so I decided to use named pipes so I can send game events down the pipe to a client program, and send commands back – then the C++ side is just a simple framework for sending a listening on a named pipe.
I have some methods like this on the C# side of things:
private string Read()
{
byte[] buffer = new byte[4096];
int bytesRead = pipeStream.Read(buffer, 0, (int)4096);
ASCIIEncoding encoder = new ASCIIEncoding();
return encoder.GetString(buffer, 0, bytesRead);
}
private void Write(string message)
{
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] sendBuffer = encoder.GetBytes(message);
pipeStream.Write(sendBuffer, 0, sendBuffer.Length);
pipeStream.Flush();
}
What would be the equivalent methods on the C++ side of things?
After you create the pipe and have pipe handles, you read and write using the
ReadFileandWriteFileAPIs: see Named Pipe Client in MSDN for a code example.The “Named Pipe Client” section which I quoted above gives an example of how to use them.
The types of all the arguments are defined in MSDN: see ReadFile and WriteFile
You’re sending the string using
ASCIIEncoding, so you’ll receive a string of non-Unicode characters.You can convert that to a string, using the overload of the std::string constructor which takes a pointer to a character buffer plus a sencond parameter which specifies how many characters are in the buffer: