Home > other >  ctypes.create_string_buffer Python 2 vs Python 3
ctypes.create_string_buffer Python 2 vs Python 3

Time:12-21

I am trying to convert a script involving ctypes from Python 2 to 3. However, there is a difference ctypes.create_string_buffer:

import ctypes
import array
import sys

buffer = array.array('B', [0, 0, 2, 1, 7, 0, 0, 0, 0, 0, 0, 0])

if sys.version_info > (3, 0):
    # In Python 3
    sb = ctypes.create_string_buffer(bytes(buffer), len(buffer)) # Cytpes object of byte
    print (sb.raw)  # output: b'\x00\x00\x02\x01\x07\x00\x00\x00\x00\x00\x00\x00'
    print (bytearray(sb))  # output: bytearray(b'\x00\x00\x02\x01\x07\x00\x00\x00\x00\x00\x00\x00')

else:
    # In Python 2
    sb = ctypes.create_string_buffer(buffer.tostring(), len(buffer)) # Ctypes object of string
    print (sb.raw)  # human unreadable output
    print (bytearray(sb))  # human unreadable output

How can I get similar Python 2 output in Python 3?

CodePudding user response:

Replace the calls to print with calls to sys.stdout.buffer.write.

  • Related