[RTX5][Memory] 使用OS自带的内存管理 osRtxMemoryAlloc() osRtxMemoryFree()
文章目录
- 一、声明内存管理函数
- 二、添加文件
- (1) lib版本,无需添加,直接使用
- (2)源文件版本 (旧版本需要手动添加,V5.5.3不需要)
- 三、函数使用
- (1)函数定义
- (2)Demo
官方默认的RTX5是不能直接使用内存管理的,因为RTX5为了通过车规验证,所以把内存管理隐藏了
一、声明内存管理函数
// Memory Heap Library functions
extern uint32_t osRtxMemoryInit (void *mem, uint32_t size);
extern void *osRtxMemoryAlloc(void *mem, uint32_t size, uint32_t type);
extern uint32_t osRtxMemoryFree (void *mem, void *block);
二、添加文件
(1) lib版本,无需添加,直接使用

(2)源文件版本 (旧版本需要手动添加,V5.5.3不需要)

如果没有,则手动添加:
rtx_memory.c x:\Keil_v5\Arm\Packs\ARM\CMSIS\5.8.0\CMSIS\RTOS2\RTX\Source\
三、函数使用
(1)函数定义
void* os_malloc(uint32_t size);
void* os_calloc(uint32_t size);
void os_free(void p);
mem_info_t os_get_memory_info(void);
注:如果想使用malloc() free(),则需要重定义。
__asm(“.global __use_no_heap_region\n\t”); //声明不使用C库的堆
void* malloc(size_t size) {
return os_malloc(size);
}
void free(void* p) {
os_free§;
}
(2)Demo
// Memory Pool Header structure
typedef struct {uint32_t size; // 最大内容量(Byte)uint32_t used; // 当前使用内存量(Byte)
} mem_info_t;#ifdef LISUN_SDK
#include "ls_syscfg.h"
#else
#define LS_MEMORY_SIZE (512)
#endif// Memory Heap Library functions
extern uint32_t osRtxMemoryInit (void *mem, uint32_t size);
extern void *osRtxMemoryAlloc(void *mem, uint32_t size, uint32_t type);
extern uint32_t osRtxMemoryFree (void *mem, void *block);static uint64_t g_heap_size[LS_MEMORY_SIZE/8];
uint8_t g_mem_init = false;__asm(".global __use_no_heap_region\n\t"); //声明不使用C库的堆
void* malloc(size_t size) {return os_malloc(size);
}void free(void* p) {os_free(p);
}os_status os_kernel_initialize(void) {if (osRtxMemoryInit(g_heap_size, LS_MEMORY_SIZE))g_mem_init = true;return (os_status)osKernelInitialize();
}void* os_malloc(uint32_t size) {if (!g_mem_init) return NULL;__asm volatile ("cpsid i" : : : "memory");char *p = osRtxMemoryAlloc(g_heap_size, size, 0);__asm volatile ("cpsie i" : : : "memory");return p;
}void* os_calloc(uint32_t size) {if (!g_mem_init) return NULL;__asm volatile ("cpsid i" : : : "memory");char *p = osRtxMemoryAlloc(g_heap_size, size, 0);__asm volatile ("cpsie i" : : : "memory");return p;
}void os_free(void *p) {if (!g_mem_init) return;__asm volatile ("cpsid i" : : : "memory");osRtxMemoryFree(g_heap_size, p);__asm volatile ("cpsie i" : : : "memory");
}mem_info_t* os_get_memory_info(void) {if (!g_mem_init) return NULL;return (mem_info_t*)g_heap_size;
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
