Data transfer from C++ to Python through pipes (pywin32)

Viewed 102

I have C++ code to send some string through pipe (in standart main function):

        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);

Also I have Python code to receive this:

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

The first I run C++ code, then I start my Python-script. C++ last output is "Sending data to pipe...". So I get error 231, which means "All instances of pipe are busy".

What I need to fix this problem?

P. S. Python 3.6, Windows 7, C++ 11.

1 Answers

Access Denied (error 5) indicates that you have network sharing restricted on your computer. Try:

  • From Network and Sharing Center, turn on all sharing.
  • Turn off password protected sharing.
  • Get your PC IP address from any whatsmyip site, then test it by pinging IP using cmd prompt.
Related