【问题标题】:Data transfer from C++ to Python through pipes (pywin32)通过管道从 C++ 到 Python 的数据传输 (pywin32)
【发布时间】:2021-07-09 11:07:49
【问题描述】:

我有 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,这意味着“所有管道实例都忙”。

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

P。 S. Python 3.6、Windows 7、C++ 11。

【问题讨论】:

    标签: python c++ pipe ipc pywin32


    【解决方案1】:

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

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

    【讨论】:

    • 抱歉,我编辑了我的问题。我收到错误 231,这意味着“所有实例都忙”。
    • 在末尾添加行:system("pause"); 以暂停特定实例。
    • 我知道了,但问题没有解决
    • 尝试手动删除L"\\\\.\\pipe\\example",然后尝试。
    • 我在关闭管道 (remove("\\\\.\\pipe\\example")) 后执行了此操作,但它不起作用。我仍然收到 231 错误。
    猜你喜欢
    • 1970-01-01
    • 2018-12-19
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 2021-10-02
    相关资源
    最近更新 更多