简体   繁体   English

如何在 C API 中创建 Python 字节对象

[英]How do I create a Python bytes object in the C API

I have a Numpy vector of bool s and I'm trying to use the C API to get a bytes object as quickly as possible from it.我有一个bool的 Numpy 向量,我正在尝试使用 C API 尽快从中获取bytes对象。 (Ideally, I want to map the binary value of the vector to the bytes object.) (理想情况下,我想将向量的二进制值映射到字节对象。)

I can read in the vector successfully and I have the data in bool_vec_arr .我可以成功读取向量,并且我在bool_vec_arr有数据。 I thought of creating an int and setting its bits in this way:我想过创建一个int并以这种方式设置它的位:

PyBytesObject * pbo; 
int byte = 0;
int i = 0;
while ( i < vec->dimensions[0] )  
{
    if ( bool_vec_arr[i] )
    {
        byte |= 1UL << i % 8;
    }
    i++;
    if (i % 8 == 0)
    {
        /* do something here? */
        byte = 0;
    }
}
return PyBuildValue("S", pbo); 

But I'm not sure how to use the value of byte in pbo .但我不确定如何在pbo使用 byte 的值。 Does anyone have any suggestions?有没有人有什么建议?

You need to store the byte you've just completed off.您需要存储刚刚完成的字节。 Your problem is you haven't made an actual bytes object to populate, so do that.你的问题是你没有制作一个实际的bytes对象来填充,所以这样做。 You know how long the result must be (one-eighth the size of the bool vector, rounded up), so use PyBytes_FromStringAndSize to get a bytes object of the correct size, then populate it as you go.您知道结果必须有多长(bool 向量大小的八分之一,四舍五入),因此使用PyBytes_FromStringAndSize获取正确大小的bytes对象,然后PyBytes_FromStringAndSize填充它。

You'd just allocate with:你只需分配:

// Preallocate enough bytes
PyBytesObject *pbo = PyBytes_FromStringAndSize(NULL, (vec->dimensions[0] + 7) / 8);
// Put check for NULL here

// Extract pointer to underlying buffer
char *bytebuffer = PyBytes_AsString(pbo);

where adding 7 then dividing by 8 rounds up to ensure you have enough bytes for all the bits, then assign to the appropriate index when you've finished a byte, eg:添加 7 然后除以 8 舍入以确保所有位都有足够的字节,然后在完成一个字节后分配给适当的索引,例如:

if (i % 8 == 0)
{
    bytebuffer[i / 8 - 1] = byte;  // Store completed byte to next index
    byte = 0;
}

If the final byte might be incomplete, you'll need to decide how to handle this (do the pad bits appear on the left or right, is the final byte omitted and therefore you shouldn't round up the allocation, etc.).如果最后一个字节可能不完整,您需要决定如何处理(填充位出现在左侧还是右侧,是否省略了最后一个字节,因此您不应该舍入分配等)。

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

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