【问题标题】:Copy const struct in flash to "normal" struct in RAM将闪存中的 const 结构复制到 RAM 中的“普通”结构
【发布时间】:2018-05-09 01:10:19
【问题描述】:

这是我所拥有的,但仍然存在问题 - 编译器无法识别“my_reg”结构类型。

../Source/functions.c:609:16: error: 'my_reg' undeclared (首先在这个函数中使用) ModBusIDReg = (my_reg)const_ModBusIDReg;

// define structure in flash with constants

struct
{
  const unsigned char Reg00[32];
  const unsigned char Reg01[32];
  const unsigned char Reg02[32];
  const unsigned short Reg03;
  const unsigned short Reg04;
} const_ModBusIDReg =
{
  "My String 1" ,
  "My String 2" ,
  "My String 3" ,
   0 ,
   0
};


// define structure in RAM, tag name "my_reg"

struct my_reg
{
  unsigned char Reg00[32];
  unsigned char Reg01[32];
  unsigned char Reg02[32];
  unsigned short Reg03;
  unsigned short Reg04;
} ModBusIDReg;


// This statement is located in InitSys function.
// Both of the files where the structures were
// defined are included at the top of the file 
// where InitSys function resides.
// Make a copy of const_ModBusIDReg from
// flash into ModBusIDReg in RAM.


ModBusIDReg = (my_reg)const_ModBusIDReg;

关于如何进行直接分配的任何想法?

【问题讨论】:

  • memcpy() 是执行此操作的适当且有效的方法。

标签: c struct copy constants


【解决方案1】:

这样的类型转换应该可以解决编译器错误:

ModBusIDReg = (my_reg)const_ModBusIDReg;

或者你可以使用memcpy():

memcpy(&ModBusIDReg, &const_ModBusIDReg, sizeof(my_reg));

(使用 memcpy() 的旁注:在某些情况下,内存对齐可能是一个问题。但我不是 c 专家。在 GCC 的情况下使用 compiler-specific attributespacked 可能会有所帮助, 定义结构时,取决于平台、编译器、使用的变量类型。)

您还可以在自定义复制函数中单独复制结构的成员,并初始化未使用的部分(如果有)。这将是干净的、非常清晰/明确的,并且类似于 C++ 中使用的复制构造函数/赋值运算符(正确处理深拷贝)。


编辑: 由于您上次编辑后无法在上方添加评论,因此我在此处添加评论:

./Source/functions.c:609:16: error: 'my_reg' undeclared (第一次使用 这个函数) ModBusIDReg = (my_reg)const_ModBusIDReg;

在 C 中,您可以在结构类型声明中使用 typedef,以避免在整个代码中重复 struct 关键字(在 here 或 @ 中详细解释987654324@):

typedef struct { ... } foo;
foo x;

这里有一个例子来说明上面提到的想法:

/* gcc -Wall -o copy_test copy_test.c && ./copy_test */

#include <stdio.h>
#include <string.h>

typedef struct {
    int var;
} my_struct;

int my_copy_func(my_struct *dst, const my_struct *src)
{
    if (!dst || !src)
        return -1;
    dst->var = src->var;
    return 0;
}

int main()
{
    const my_struct a = { .var = 42 };
    my_struct b, c, d;
    c = (my_struct)a;
    memcpy(&b, &a, sizeof(b));
    my_copy_func(&d, &a);
    printf("b.var = %d\r\n", b.var);
    printf("c.var = %d\r\n", c.var);
    printf("d.var = %d\r\n", d.var);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2012-02-25
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    相关资源
    最近更新 更多