views:

106

answers:

1

I'm trying to convert a 16 byte blob of data returned by socket.inet_pton into a ctypes array of unsigned bytes. My data structure looks like this:

class in6_addr(ctypes.Structure):
    _fields_ = (("Byte", ctypes.c_ubyte * 16),)

And the blob is just:

data = socket.inet_pton(socket.AF_INET6, "2001::3")

However, these attempts get errors:

sin6 = in6_addr()

# TypeError: expected c_ubyte_Array_16 instance, got str
sin6.Byte = data
# TypeError: cast() argument 2 must be a pointer type, not c_ubyte_Array_16
sin6.Byte = ctypes.cast(data, ctypes.c_ubyte * 16)
# TypeError: incompatible types, LP_c_ubyte instance instead of c_ubyte_Array_16 instance
sin6.Byte = ctypes.cast(data, ctypes.POINTER(ctypes.c_ubyte))

All of the code: http://codepad.org/2cjyVXBA

Any ideas what type I need to cast to?

+2  A: 

I might be completely wrong here (and it does seem a bit complex) but this works for me:

sin6.Byte = (ctypes.c_ubyte*16)(*list(bytearray(data)))

I had to convert the data into a list of integers and unpack them for the constructor. There must be an easier way!

Scott Griffiths