Implementing a Temporary Key-Value Cache in LVGL-C

LVGL is developed in C, which is a powerful language but often requires custom implementations of complex data structures for real-world projects. LVGL follows an object-oriented programming design approach. Based on this concept, we can design a Map-like data structuer similar to Java to cache temporary data, facilitating UI data binding in complex LVGL GUI interactiosn.

Creating Code Files: map.h and map.c

1. Data Structure Encapsulation


// Define map item type
typedef struct
{
    int key;
    void *value;
} lvgl_cache_item_t;

// Allocate map structure
typedef struct
{
    int capacity;
    lvgl_cache_item_t *entries;
} lvgl_cache_map_t;

2. Function Declarations


#include <stdlib.h>
#define CACHE_CAPACITY 2 // Size depends on number of keys
#define SPEED_DATA_KEY 0
#define WATER_DATA_KEY 1

// Cache map
static lvgl_cache_map_t *cache = NULL;

// Initialize cache map
void lvgl_cache_init(int initial_size);
// Set value in cache map
void lvgl_cache_set(const int key, void *value);
// Get value from cache map
void *lvgl_cache_get(const int key);
// Free cache map resources
void lvgl_cache_free();
</stdlib.h>

3. Function Definitions


// Key-value data structure for retrieval
/**
 * Initialize cache data
 */
void lvgl_cache_init(int initial_size)
{
    cache = malloc(sizeof(lvgl_cache_map_t));
    cache->capacity = initial_size;
    cache->entries = malloc(sizeof(lvgl_cache_item_t) * initial_size);
    // Initialize cache entries
    for (int i = 0; i < initial_size; i++)
    {
        cache->entries[i].key = i;
        cache->entries[i].value = NULL;
    }
}

/**
 * Add key-value pair
 */
void lvgl_cache_set(const int key, void *value)
{
    if (cache == NULL || key < 0 || value == NULL)
        return;
    if (cache->entries[key].key == key)
    {
        cache->entries[key].value = value;
    }
}

/**
 * Retrieve value by key
 */
void *lvgl_cache_get(const int key)
{
    if (cache == NULL || key < 0)
        return NULL;
    if (cache->entries[key].key >= 0)
    {
        return cache->entries[key].value;
    }
    return NULL;
}

/**
 * Free cache resources
 */
void lvgl_cache_free()
{
    if (cache == NULL)
        return;
    free(cache->entries);
    free(cache);
}

4. Initialization and Usage Example


// Initialize temporary cache
lvgl_cache_init(CACHE_CAPACITY);
// Store data in cache by key
lvgl_cache_set(SPEED_DATA_KEY, 100);
lvgl_cache_set(WATER_DATA_KEY, "23");
// Retrieve data from cache by key
PRINT("lvgl_cache_get SPEED_DATA_KEY = %d \n", lvgl_cache_get(SPEED_DATA_KEY));
PRINT("lvgl_cache_get WATER_DATA_KEY = %s \n", lvgl_cache_get(WATER_DATA_KEY));

Tags: LVGL c programming key-value cache Data Structures Embedded Systems

Posted on Wed, 02 Sep 2026 16:06:28 +0000 by chapm4