官方默认的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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App