Reputation: 49
In C we have
struct temp
{
unisgned int i[10];
char a[2][10];
}temp;
Like this i am making one structure in python:
integer_aray=[1,2,3,4,5]
string_array=["hello","world"]
format_="Qs"
temp = namedtuple("temp","i a")
temp_tuple = temp(i=integer_array,a=string_array)
string_to_send = struct.pack(format_, *temp_tuple)
When i am trying like this python 2.7 giving error
string_to_send = struct.pack(format_, *temp_tuple)
error: cannot convert argument to integer
I have to send the python structure as and array of integer and as an array of strings.Is there any way we can do by sending arrays without using ctypes ?
Upvotes: 0
Views: 937
Reputation: 148870
If you want to pack the equivalent of the C struct
struct temp
{
unsigned int i[10];
char a[2][10];
};
you will use the format "10I10s10s"
where 10I
stands for 10 4-byte unsigned integers in native order, and each 10s
represents a byte string of size 10.
In Python3, you could write:
l = list(range(1, 11)) # [1,2,3,4,5,6,7,8,9,10]
temp = struct.pack("10I10s10s", *l, b"hello", b"world")
print(temp)
it would give (on a little endian ASCII platform):
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t\x00\x00\x00\n\x00\x00\x00hello\x00\x00\x00\x00\x00world\x00\x00\x00\x00\x00'
which is compatible with the C temp
struct on a 32 bits little endian system.
Upvotes: 1
Reputation: 213296
char *a[2][10];
is a 2D array of 2x10 pointers.
You probably meant to do either char a[2][10];
which is an array of 2 C strings, each 9+1 characters long. Or perhaps char* a[2]
, which is two pointers to characters (possibly arrays).
Upvotes: 0