python convert string to bytes error: ValueError: bytes too long

Viewed 598

I have this definition of Structure class with cytpes, which will be sent over socket:

import ctypes

class MyStructure(Structure):
      _pack_ = 1
      _fields_ = [("field1", c_int),
                 ("field2", c_longlong),
                 ("data", c_char * 1000)]

And the following code:

st = MyStructure()
strlist = str([i % 256 in range(1000)]) // 0,1,2,3,...
st.data = str.encode(strlist) // exception

Last line raises an exception:

ValueError: bytes too long (3000, maximum length 1000)

Pass partial string will solve it but i don't understand the reason for the error:

st.data = str.encode(strlist)[:1000] // OK

Also, i'd like to know which conversion is the most straight-forward to do into a large 'bytes' type variable such as st.data (don't want to assign one by one)?

2 Answers

As Jon Clements mentioned in the first comment, converting string list to int turned any int value into three characters - the value, comma and space. For example, converting this int list intlist = [5, ] into string list strlist = str(intlist) will produde len(strlist) as 3!

A different way to insert data into the 'bytes' type could be:

st.data = b''
 for i in range(1000):
    st.data += (i % 256).to_bytes(1, "little")

Create a byte string instead of a Unicode string:

from ctypes import *

class MyStructure(Structure):
      _pack_ = 1
      _fields_ = [("field1", c_int),
                 ("field2", c_longlong),
                 ("data", c_char * 1000)]

st = MyStructure()
st.data = bytes([i % 256 for i in range(1000)])
Related