我想通过管道将数据从C ++ DLL文件发送到C#pip服务器。服务器已经编程,并且使用C#客户端可以正常运行数据。
我的简单C#客户端代码:
System.IO.Pipes.NamedPipeClientStream pipeClient = new System.IO.Pipes.NamedPipeClientStream(".", "testpipe", System.IO.Pipes.PipeDirection.InOut, System.IO.Pipes.PipeOptions.None);
if (pipeClient.IsConnected != true) { pipeClient.Connect(); }
StreamReader sr = new StreamReader(pipeClient);
StreamWriter sw = new StreamWriter(pipeClient);
try
{
sw.WriteLine("Test Message");
sw.Flush();
pipeClient.Close();
}
catch (Exception ex) { throw ex; }
}
但是,我不能在C ++中实现这个客户端。我需要哪些头文件? 你能给我一个简单的例子吗?谢谢!
编辑: 感谢您的回复! 为了测试它,我创建了一个C ++程序,现在编译如下:
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE pipe = CreateFile(
L"testpipe",
GENERIC_READ, // only need read access
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (pipe == INVALID_HANDLE_VALUE) {
// look up error code here using GetLastError()
DWORD err = GetLastError();
system("pause");
return 1;
}
// The read operation will block until there is data to read
wchar_t buffer[128];
DWORD numBytesRead = 0;
BOOL result = ReadFile(
pipe,
buffer, // the data from the pipe will be put here
127 * sizeof(wchar_t), // number of bytes allocated
&numBytesRead, // this will store number of bytes actually read
NULL // not using overlapped IO
);
if (result) {
buffer[numBytesRead / sizeof(wchar_t)] = '?'; // null terminate the string
// wcout << "Number of bytes read: " << numBytesRead << endl;
// wcout << "Message: " << buffer << endl;
} else {
// wcout << "Failed to read data from the pipe." << endl;
}
// Close our pipe handle
CloseHandle(pipe);
system("pause");
return 0;
return 0;
}
但是,当我运行它时,(pipe == INVALID_HANDLE_VALUE)为真。 调试显示DWORD err = GetLastError();尽管服务器正在运行,但其值为2。 有人有想法吗?
答案 0 :(得分:1)
你可以在网上找到很多例子。搜索命名管道示例c ++。 例如:http://www.avid-insight.co.uk/2012/03/introduction-to-win32-named-pipes-cpp/