【问题标题】:Shared pointer without malloc AVR没有 malloc AVR 的共享指针
【发布时间】:2015-04-30 12:03:52
【问题描述】:

标题可能不清楚,我举个例子吧。

我正在尝试用 C 语言创建一个“数据流”系统。

输入STREAM:

typedef struct {
    void (*tx) (uint8_t b);
    uint8_t (*rx) (void);
} STREAM;

我有一个文件 uart.huart.c,它应该为 UART 提供一个 STREAM

我决定最好将它作为一个指针公开,这样它就可以在不使用 & 符号的情况下传递给函数。

这是我想使用的功能类型(示例):

/** Send signed int */
void put_i16(const STREAM *p, const int16_t num);

这是我的 UART 文件:

uart.h

extern STREAM* uart;

uart.c

// Shared stream instance
static STREAM _uart_singleton;
STREAM* uart;

void uart_init(uint16_t ubrr) {
    // uart init code here

    // Create the stream
    _uart_singleton.tx = &uart_tx; // function pointers
    _uart_singleton.rx = &uart_rx;

    uart = &_uart_singleton; // expose a pointer to it
}

对此我不确定。它有效,但它是正确的方法吗?我应该改用 Malloc 吗?

为什么我问这个,这是一个库代码,我希望它尽可能干净和“正确”

【问题讨论】:

  • 无需使用malloc。你的代码在我看来很好。
  • 所以以这种方式使用堆变量可以吗?只是确保,我对这个更高级的 C 不是很有经验
  • 你的代码中没有堆变量,只有全局变量。
  • 哦,我以为_uart_singleton 存在于堆中。无论如何,这就是我的意思
  • 谷歌data vs bss了解更多信息。

标签: c pointers embedded avr


【解决方案1】:

全局指针是不必要的(as are all globals),而且不安全——它是非常量的;任何可以访问指针的代码都可以修改_uart_singleton

uart.h

const STREAM* getUart() ;
...

uart.c

// Shared stream instance
static STREAM _uart_singleton = {0} ;

const STREAM* getUart()
{
    // Return singleton if initialised, 
    // otherwise NULL
    return _uart_singleton.rx != 0 && 
           _uart_singleton.tx != 0 ? _uart_singleton :
                                     NULL ;
}

void uart_init(uint16_t ubrr) 
{
    // uart init code here

    // Create the stream
    _uart_singleton.tx = &uart_tx; // function pointers
    _uart_singleton.rx = &uart_rx;
}

只要访问STREAM 成员的所有函数都使用uart.c 定义,那么您还可以通过使用不完整的方式将STREAM 设为不透明类型(Lundin 在评论中的建议)。头文件中的结构声明如下:

uart.h

struct sStream ;
typedef struct sStream STREAM ;

const STREAM* getUart() ;
...

uart.c

// Shared stream instance
struct sStream 
{
    void (*tx) (uint8_t b);
    uint8_t (*rx) (void);

} _uart_singleton = {0} ;

const STREAM* getUart()
{
    // Return singleton if initialised, 
    // otherwise NULL
    return _uart_singleton.rx != 0 && 
           _uart_singleton.tx != 0 ? _uart_singleton :
                                     NULL ;
}

...

这可以防止 uart.c 之外的任何代码直接调用 rxtx 函数或访问任何其他成员。

【讨论】:

  • getUart() 可以将其作为参考而不是指针返回。 (如果适合您的需要,则为 const 参考)。
  • @GrahamS 你是什么意思?指针和引用不一样吗?
  • 不完全是@MightyPork,引用永远不能为空,并且在创建后不能更改为引用其他内容。一般来说,这些限制意味着引用比指针使用起来更“安全”一些。但它们是 C++ 类型,我刚刚注意到这个问题只与 C 有关,所以指针是 :)
  • @GrahamS 实际上,引用只是一个等于type* const 的常量指针。它只是带有更简单的语法,因此 C++ 程序员不必担心*-> 之类的运算符:)
  • @Lundin :用你不完整的类型建议详细回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-14
  • 1970-01-01
  • 1970-01-01
  • 2017-08-22
相关资源
最近更新 更多