0

It is possible to pass binary data from C to Python. For example it is possible to pass the bytes of state to Python?. Maybe using some of these functions https://docs.python.org/3/c-api/bytes.html?

uint32_t state[3] = {0x00000300, 0x00001100, 0x00022200};
unsigned char charstate[1420];
memcpy(charstate, (unsigned char *)state, sizeof(uint32_t)*3);
printf("charstate: %s", charstate);
return PyBytes_FromString(charstate);

I tried PyBytes_FromString without success (maybe because state is not a string)

EDITED

Also, I tried @John Zwinck answer

   uint32_t state[3] = {0x00000300, 0x00001100, 0x00022200};
   char charstate[12];
   memset(charstate, 0, 12);
   memcpy(charstate, state, sizeof(uint32_t)*3);
   return PyBytes_FromStringAndSize(charstate, sizeof(uint32_t)*3);

Now I see in Python [0, 3, 0, 0, 0, 17, 0, 0, 0, 34, 2, 0] which is not equal to state (in C).

1
  • How did you try? Using socket? Commented Jan 16, 2021 at 10:08

1 Answer 1

3

PyBytes_FromString() assumes you pass it a null-terminated string. But you have 00 bytes in the middle of your string, which will make the Python string shorter than you want.

Instead, do this:

PyBytes_FromStringAndSize(charstate, sizeof(uint32_t)*3)
Sign up to request clarification or add additional context in comments.

4 Comments

The printf() format specifier %s also assumes the same, a NUL-terminated string, so that needs fixing as well.
Thanks @John Zwinck, I think we are very close to the result. Now I see this in python [0, 3, 0, 0, 0, 17, 0, 0, 0, 34, 2, 0]. It is not equal to {0x00000300, 0x00001100, 0x00022200} (in C). What do you think is happening?
@Jhon Zwinck I understand most significant bit is left
OK so it's working now then. The order of the bytes is reversed within each uint32_t because you are on a "little endian" computer, so the number 0x00000300 is stored as 00 03 00 00.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.