简体   繁体   English

使用“用 C 扩展 Python”将二进制数据从 C 传递到 Python

[英]Passing binary data from C to Python using “Extending Python with C”

It is possible to pass binary data from C to Python.可以将二进制数据从 C 传递到 Python。 For example it is possible to pass the bytes of state to Python?.例如,可以将 state 的字节传递给 Python?。 Maybe using some of these functions https://docs.python.org/3/c-api/bytes.html ?也许使用其中一些功能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)我尝试 PyBytes_FromString 没有成功(可能是因为 state 不是字符串)

EDITED已编辑

Also, I tried @John Zwinck answer另外,我尝试了@John Zwinck 的回答

   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 [0, 3, 0, 0, 0, 17, 0, 0, 0, 34, 2, 0] 中看到不等于 state(在 C 中)。

PyBytes_FromString() assumes you pass it a null-terminated string. PyBytes_FromString()假设您将一个以空字符结尾的字符串传递给它。 But you have 00 bytes in the middle of your string, which will make the Python string shorter than you want.但是你的字符串中间有00个字节,这会使 Python 字符串比你想要的短。

Instead, do this:相反,请执行以下操作:

PyBytes_FromStringAndSize(charstate, sizeof(uint32_t)*3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM