相同大小的int与BGRA并集会产生不同的结果

int vs. BGRA union of the same size produces different results

本文关键字:结果 BGRA int      更新时间:2023-10-16

有人能解释一下下面三个函数之间的区别吗?

typedef union
{
    std::uint8_t B, G, R, A;
    std::uint32_t Colour;
} BGRA;

第一:

void Image::process_pixels(void* out, void* in)
{
    unsigned int i, j;
    BGRA* pOut = (BGRA*)out;
    unsigned char* pIn = (unsigned char*)in;
    for (i = 0; i < height; ++i)
    {
        for (j = 0; j < width; ++j)
        {
            pOut->B = *(pIn++);
            pOut->G = *(pIn++);
            pOut->R = *(pIn++);
            pOut->A = *(pIn++);
            ++pOut;
        }
    }
}

第二:

void Image::process_pixels(void* out, void* in)
{
    unsigned int i, j;
    unsigned int* pOut = (unsigned int*)out;
    unsigned int* pIn = (unsigned int*)in;
    for (i = 0; i < height; ++i)
    {
        for (j = 0; j < width; ++j)
        {
            *pOut++ = *pIn++
        }
    }
}

第三:

void Image::process_pixels(void* out, void* in)
{
    unsigned int i, j;
    BGRA* pOut = (BGRA*)out;
    unsigned char* pIn = (unsigned char*)in;
    for (i = 0; i < height; ++i)
    {
        for (j = 0; j < width; ++j)
        {
            memcpy(pOut, pIn, sizeof(int));
            ++pOut;
            pIn += sizeof(int);
        }
    }
}

如果我使用第二个或第三个实现,代码运行良好。图像渲染正确。但是,如果我使用第一个实现,则没有任何内容能够正确呈现。

我可以保证sizeof(BGRA) = sizeof(int)。我可以保证像素的BGRA格式。然而不知怎么的,我得到了不同的结果。。

我一辈子都看不到前两个实现和后两个实现之间的区别。有什么想法吗?

typedef union
{
    std::uint8_t B, G, R, A;
    std::uint32_t Colour;
} BGRA;

这里,BGRA是共享相同地址的4个元素
您应该将BGRA包含在类似的结构中

typedef union
{
    struct {
        std::uint8_t B, G, R, A;
    } Components;
    std::uint32_t Colour;
} BGRA;

这个联盟有五个成员。你似乎认为它只有两个。