Passing binary data from C to Python using "Extending Python with C"

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).

python
c
asked on Stack Overflow Jan 16, 2021 by Juan • edited Jan 16, 2021 by Juan

1 Answer

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)
answered on Stack Overflow Jan 16, 2021 by John Zwinck

User contributions licensed under CC BY-SA 3.0