本帖最后由 Simon21ic 于 2017-1-6 20:43 编辑
很少看到APP转嵌入式的,不过你如果有兴趣的话,我就贴一些代码
你能想到宏的方式,估计你也大概猜到会是这么实现了吧
好处是不需要黏贴复制,直接在C语言中使用类似模板的功能;坏处是,这些代码基本没办法调试
具体就不做说明了,只是简单的通用内存池的实现
void vsfpool_init(struct vsfpool_t *pool)
{
memset(pool->flags, 0, (pool->num + 31) >> 3);
}
void* vsfpool_alloc(struct vsfpool_t *pool)
{
uint32_t index = mskarr_ffz(pool->flags, (pool->num + 31) >> 5);
if (index >= pool->num)
{
return NULL;
}
mskarr_set(pool->flags, index);
return (uint8_t *)pool->buffer + index * pool->size;
}
void vsfpool_free(struct vsfpool_t *pool, void *buffer)
{
uint32_t index = ((uint8_t *)buffer - (uint8_t *)pool->buffer) / pool->size;
if (index < pool->num)
{
mskarr_clr(pool->flags, index);
}
}
// pool
struct vsfpool_t
{
uint32_t *flags;
void *buffer;
uint32_t size;
uint32_t num;
};
#define VSFPOOL_DEFINE(name, type, num) \
struct vsfpool_##name##_t\
{\
struct vsfpool_t pool;\
uint32_t mskarr[((num) + 31) >> 5];\
type buffer[(num)];\
} name
#define VSFPOOL_INIT(p, type, n) \
do {\
(p)->pool.flags = (p)->mskarr;\
(p)->pool.buffer = (p)->buffer;\
(p)->pool.size = sizeof(type);\
(p)->pool.num = (n);\
vsfpool_init((struct vsfpool_t *)(p));\
} while (0)
#define VSFPOOL_ALLOC(p, type) \
(type *)vsfpool_alloc((struct vsfpool_t *)(p))
#define VSFPOOL_FREE(p, buf) \
vsfpool_free((struct vsfpool_t *)(p), (buf))
void vsfpool_init(struct vsfpool_t *pool);
void* vsfpool_alloc(struct vsfpool_t *pool);
void vsfpool_free(struct vsfpool_t *pool, void *buffer);
|