简体   繁体   English

用Python打包和用C解包

[英]Packing in Python and Unpacking in C

I'm trying to pack integers as bytes in python and unpack them in C. So in my python code I have something like 我试图将整数作为字节打包在python中,并在C中解压缩它们。所以在我的python代码中,我有类似

testlib = ctypes.CDLL('/something.so')
testlib.process(repr(pack('B',10)))

which packs 10 as a byte and calls the function "process" in my C code. 它将10打包为一个字节,并在我的C代码中调用函数“ process”。

What do I need in my C code to unpack this packed data? 我需要在C代码中解压缩此打包数据吗? That is, what do I need to do to get 10 back from the given packed data. 也就是说,我该怎么做才能从给定的打包数据中取回10。

Assuming you have a 10 byte string containing 10 integers, just copy the data. 假设您有一个包含10个整数的10字节字符串,只需复制数据即可。

char packed_data[10];
int unpacked[10];

int i;
for(i = 0; i < 10; ++i)
    unpacked[i] = packed_data[i];

... or using memcpy ...或使用memcpy

On the other hand, if you're using 4 bytes pr int when packing, you can split the char string in C and use atoi on it. 另一方面,如果在打包时使用4个字节的pr int,则可以在C中拆分char字符串,并在其上使用atoi How are you exchanging data from Python to C ? 您如何将数据从Python交换到C?

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

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