For cases involving C++ or third-party libraries, using RT-Thread memory management functions would require extensive code modifications. Here, we present an alternative approach: redefine standard C memory allocation functions to use RT-Thread’s memory management, enabling dynamic use of PSRAM with a single configuration. The code is as follows:
#include "rtthread.h"
static uint8_t opus_heap_pool[5000 * 1024] L2_RET_BSS_SECT(opus_heap_pool);
static struct rt_memheap opus_memheap;
// Redefine standard memory management functions
void *malloc(size_t size) __attribute__((alias("opus_heap_malloc")));
void free(void *ptr) __attribute__((alias("opus_heap_free")));
void *realloc(void *ptr, size_t new_size) __attribute__((alias("opus_heap_realloc")));
void *calloc(rt_size_t nelem, rt_size_t elsize) __attribute__((alias("opus_heap_calloc")));
int opus_heap_init(void)
{
rt_memheap_init(&opus_memheap, "opus_memheap", (void *)opus_heap_pool,
sizeof(opus_heap_pool));
return 0;
}
INIT_BOARD_EXPORT(opus_heap_init); // Key: Use board-level initialization export macro
void *opus_heap_malloc(uint32_t size)
{
return rt_memheap_alloc(&opus_memheap, size);
}
void opus_heap_free(void *p)
{
rt_memheap_free(p);
}
void *opus_heap_realloc(void *ptr, uint32_t newsize)
{
return rt_memheap_realloc(&opus_memheap, ptr, newsize);
}
void *opus_heap_calloc(uint32_t num, uint32_t size)
{
return rt_memheap_calloc(&opus_memheap, num, size);
}