gpt4 book ai didi

c - 一起使用静态分配和封装

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:56 24 4
gpt4 key购买 nike

<分区>

看完Design Patterns for Embedded Systems in C我改变了实现设备驱动程序的方式。 书中建议典型的设备驱动程序头文件具有此实现。

/* Encapsulated device handle using 'opaque' pointer */
typedef struct device device_t;

/* Allocated dynamically */
device_t* device_create( i2c_t* bus, const uint8_t address );

void device_destroy( device_t* me );
int device_initialize( device_t* me );
int device_deinitialize( device_t* me );
int device_isAvailable( device_t* me );
int device_configure( device_t* me, const device_config_t config );

是的,我知道 C 不是面向对象的,但我喜欢它的代码干净整洁。我稍微更改了代码。我牺牲了设备句柄封装以便能够静态分配它。

/* Public(no ecapsulation) device handle */
typedef struct device
{
int public_member1;
int public_member2;
} device_t;

/* Allocated statically */
device_t device_create( i2c_t* bus, const uint8_t address );

int device_initialize( device_t* me );
int device_deinitialize( device_t* me );
int device_isAvailable( device_t* me );
int device_configure( device_t* me, const device_config_t config );

如果可能的话,我宁愿不动态分配,因为我担心内存碎片,但如果这是一个好的设计方案,我会这样做。由于我的项目是嵌入式的并且我的目标是 cortex-m0 我想知道我是否可以同时使用静态分配和封装..

更新:

我为上面的代码给出了两种不同的device_create实现

动态地:

device_t* device_create( i2c_t* bus, const uint8_t address )
{
/* Check input */
if( bus == NULL )
{
return NULL;
}

/* Create handle */
device_t* aux = (device_t*)malloc( sizeof( device_t ) );
if( aux == NULL )
{
return NULL;
}

/* Initialize handle */
init( aux, bus, address );

/* Return handle */
return aux;
}

静态:

device_t device_create( i2c_t* bus, const uint8_t address )
{
/* Check input */
if( bus == NULL )
{
return NULL;
}

/* Create handle */
device_t aux;

/* Initialize handle */
init( &aux, bus, address );

/* Return handle */
return aux;
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com