0

我想通过管道将数据从 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。有人有想法吗?

4

1 回答 1

1

你可以在网上找到很多例子。搜索命名管道示例 c++。例如:http ://www.avid-insight.co.uk/2012/03/introduction-to-win32-named-pipes-cpp/

于 2013-05-07T22:59:31.273 回答