hakril / PythonForWindows

A codebase aimed to make interaction with Windows and native execution easier
BSD 3-Clause "New" or "Revised" License
569 stars 114 forks source link

samples/alpc/simple_alpc.py | TypeError: one character bytes, bytearray or integer expected #44

Closed m-doescode closed 1 year ago

m-doescode commented 1 year ago

It seems like in the file samples/alpc/simple_alpc.py there is an error which causes it not to run.

For one, there are many references to print without parentheses, not sure if this is intended but it does not run without them, so I added them beforehand.

Second, every time I run it unmodified, (apart from the edit as mentioned above) I get this error:

C:\####\pywin\samples\alpc>py simple_alpc.py
[SERV] PORT <\RPC Control\PythonForWindowsPORT> CREATED
Client pid = 2836
[SERV] Message type = 0x200a
[SERV] Received data: <b''>
[SERV] Connection request
[CLIENT] Connected: <windows.alpc.AlpcClient object at 0x000001DFF3AAE7D0>
Traceback (most recent call last):
  File "C:\####\pywin\samples\alpc\simple_alpc.py", line 48, in <module>
    alpc_client()
  File "C:\####\pywin\samples\alpc\simple_alpc.py", line 39, in alpc_client
    response = client.send_receive("Hello world !")
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\####\Python\Python311\site-packages\windows\alpc.py", line 310, in send_receive
    alpc_message.port_message.data = raw_alpc_message
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\####\Python\Python311\site-packages\windows\alpc.py", line 164, in write_data
    self.raw_buffer[self.header_size: self.header_size + len(data)] = data
    ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: one character bytes, bytearray or integer expected

Solution

It seems like you cannot use regular strings with the message data and must instead use bytes. So, the solution is simply to replace any time msg.data is set with a string with bytes:

    response = client.send_receive(b"Hello world !") # ln 39
    msg.data = str.encode("REQUEST '{0}' DONE".format(msg.data)) # ln 28

End

If you approve this issue, I will create a pull request so that this can be updated.

Upon further examination

It seems like this is related to #38 The author of the pull request attempts to solve the issue by modifying the alpc.py API, whereas my solution was to modify the sample simple_alpc.py

hakril commented 1 year ago

Hello !

Thank you for the detailed issue. Indeed the ALPC samples were not tested on python3. I made a PR inspired from your remarks that match my code habits on str/bytes issue and try to keep the display of the sample nice on py3. See #45.

Does it works for you ? If so, I will also close #38.