【问题标题】:security of a const static struct object in CC 中 const 静态结构对象的安全性
【发布时间】:2014-06-25 12:36:36
【问题描述】:

我是 C 编程的新手,我正在做一些项目,我必须在不同的源文件之间共享大量信息。

在一个源文件中,我声明并初始化了一个特定结构的变量,而在另一个文件中,我需要使用指向该变量的指针,以访问其中的信息,但不要更改它。

  1. 此变量不能在我的代码中的其他任何地方更改。
  2. 这个变量不能是全局的,它必须是静态的。

代码:

//file 1 :

typedef struct {
    bool (*decodeParameters)(void* interface, uint8_t command, uint16_t parameters[]);
    bool value;
} i_actuator_t;

static const i_actuator_t iActuator = {
    decodeActuatorParameters,  //pointer to a function in the same file 1
    false
};        //this variable has to be protected so it cannot be edited anywhere else , and it cannot be global .

i_actuator_t* getActuatorInterface (void) = {
    return &iActuator;
}

file 2,我想做这样的事情:

i_actuator_t* iActuatorPTR = getActuatorInterface();

static const 变量在这里是正确的吗? 有没有更好的解决方案?

谢谢

【问题讨论】:

    标签: c pointers struct static constants


    【解决方案1】:

    您的函数返回的指针也应标记为const。使用这个返回值的变量也应该如此。

    【讨论】:

      猜你喜欢
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多