首页 > 解决方案 > 通过管道从 C++ 到 Python 的数据传输 (pywin32)

问题描述

我有 C++ 代码通过管道发送一些字符串(在标准主函数中):

        HANDLE pipe = CreateNamedPipe(L"\\\\.\\pipe\\example",
            PIPE_ACCESS_OUTBOUND, PIPE_TYPE_BYTE, 1, 0, 0, 0, NULL);

        if (pipe == NULL || pipe == INVALID_HANDLE_VALUE) {
            cout << "Failed to create outbound pipe instance.";
            system("pause");
            return 1;
        }

        cout << "Waiting for a client to connect to the pipe..." << endl;
        // This call blocks until a client process connects to the pipe
        BOOL result = ConnectNamedPipe(pipe, NULL);

        if (!result) {
            cout << "Failed to make connection on named pipe." << endl;
            CloseHandle(pipe); // close the pipe
            system("pause");
            return 1;
        }

        cout << "Sending data to pipe..." << endl;
        // This call blocks until a client process reads all the data
        const wchar_t *data = L"*** Hello Pipe World ***";
        DWORD numBytesWritten = 0;
        result = WriteFile(pipe, data, wcslen(data) * sizeof(wchar_t), &numBytesWritten, NULL);

        if (result) {
            cout << "Number of bytes sent: " << numBytesWritten << endl;
        } else {
            cout << "Failed to send data." << endl;
        }

        CloseHandle(pipe);

我也有 Python 代码来接收这个:

quit = False
while not quit:
    try:
        handle = win32file.CreateFile(
            "\\\\.\\pipe\\example",
            win32file.GENERIC_READ,
            0,
            None,
            win32file.OPEN_EXISTING,
            0,
            None
        )
        res = win32pipe.SetNamedPipeHandleState(handle, win32pipe.PIPE_READMODE_MESSAGE, None, None)

        if res == 0:
            print(f"SetNamedPipeHandleState return code: {res}")

        while True:
            resp = win32file.ReadFile(handle, 64*1024)
            print(f"message: {resp}")
    except pywintypes.error as e:
        print(e.args[0])
        quit = True

我首先运行 C++ 代码,然后启动我的 Python 脚本。C++ 的最后一个输出是“将数据发送到管道...”。所以我收到错误 231,这意味着“所有管道实例都忙”。

我需要什么来解决这个问题?

PS Python 3.6、Windows 7、C++ 11。

标签: pythonc++pipeipcpywin32

解决方案


拒绝访问(错误 5)表示您的计算机上的网络共享受到限制。尝试:

  • 从网络和共享中心,打开所有共享。
  • 关闭受密码保护的共享。
  • 从任何 whatsmyip 站点获取您的 PC IP 地址,然后使用 cmd 提示 ping IP 来测试它。

推荐阅读