简体   繁体   English

从传递给符合MISRA规则17.4的函数的void指针参数访问所有数组元素

[英]Access to all array elements from a void pointer parameter passed to a function compliant with MISRA Rule 17.4

Only embedded C. 仅嵌入式C。

I need a function to copy unsigned data from a 4-bytes array byte per byte to an output parameter (both passed as reference). 我需要一个函数来将无符号数据从每字节4字节数组字节复制到输出参数(均作为参考传递)。 Function should be MISRA 17.4 compliant and should support different unsigned integer datatype for output parameter (considering input will always have the exact number of unsigned bytes to fill the output) 函数应符合MISRA 17.4的要求,并应为输出参数支持不同的无符号整数数据类型(考虑到输入将始终具有准确的无符号字节数来填充输出)

So my code is: 所以我的代码是:

static void copy_array(const void * src, void * dest, const uint8_t lenght_bytes)
{
    uint8_t i;
    const uint8_t * src_8 = (const uint8_t*)src;
    uint8_t * dest_8 = (uint8_t*)dest;
    for (i = 0u; i < lenght_bytes; i++)
    {
        *(dest_8 + i) = *(src_8 + i);
    }
}

static void func(void)
{
    uint8_t data[] = {0xEFu, 0xCDu, 0x0u, 0x0u};
    uint16_t dest_16;
    uint32_t dest_32;

    copy_array(data, &dest_16, sizeof(dest_16));

    data[0] = 0xEFu;
    data[1] = 0xCDu;
    data[2] = 0xABu;
    data[3] = 0x89u;

    copy_array(data, &dest_32, sizeof(dest_32));
}

So, MISRA limits pointer arithmetic operations only to array indexing, therefore, my function is not compliant. 因此,MISRA仅将指针算术运算限制为数组索引,因此,我的函数不兼容。 Any smart way to avoid the rule or to perform same operation but MISRA compliant? 有什么聪明的方法可以避免规则或执行相同的操作但符合MISRA?

First of all, this is not valid C: 首先,这是无效的C:

uint8_t data[4] = {0xEFu, 0xCDu, NULL, NULL};

Since NULL might be a null pointer constant of the form (void*)0 . 由于NULL可能是(void*)0形式的null指针常量。 Replace NULL with 0 here. 在此处将NULL替换为0


As for the old MISRA-C:2004 requirement about array indexing being the only allowed form, it was mostly nonsense and has been fixed in the current MISRA-C:2012. 至于旧的MISRA-C:2004关于数组索引是唯一允许的形式的要求,它大部分都是废话,并且在当前的MISRA-C:2012中已得到修复。 That being said, there is no need for explicit pointer arithmetic in your code, so that rule makes sense here. 话虽如此,您的代码中无需显式指针算术,因此该规则在这里有意义。

Simply fix the function like this: 只需像这样修复函数:

static void copy_array(const void* src, void* dest, const uint8_t lenght_bytes)
{
    uint8_t i;
    const uint8_t* src_8 = src;
    uint8_t* dest_8 = dest;

    for (i = 0u; i < lenght_bytes; i++)
    {
        dest_8[i] = src_8[i];
    }
}

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

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