Phenom588
Phenom588

Reputation: 81

Unpacking a C struct with Pythons struct module

I am sending a struct in binary format from C to my python script.

My C struct:

struct EXAMPLE {
    float val1;
    float val2;
    float val3;
}

How I send it:

struct EXAMPLE *ex;
ex->val1 = 5.3f;
ex->val2 = 12.5f;
ex->val3 = 15.5f;

write(fd, &ex, sizeof(struct EXAMPLE));

How I recieve:

buf = sock.recv(12)
buf = struct.unpack('f f f', buf)
print buf

But when I print it out on the python side all I get is random garbage. I'm pretty sure there is something wrong with the struct definition in python but I'm not sure what.

Upvotes: 2

Views: 134

Answers (1)

Robᵩ
Robᵩ

Reputation: 168596

This line is wrong:

write(fd, &ex, sizeof(struct EXAMPLE));

It should be:

write(fd, ex, sizeof(struct EXAMPLE));

Upvotes: 2

Related Questions