#include "lv_log_to_esp.h" static const char *TAG = "LVGL"; static void my_print(lv_log_level_t level, const char *buf) { // 1. 获取原始字符串长度 size_t buf_len = strlen(buf); // 2. 动态分配内存(比原始字符串多分配1个字节,确保安全) char *my_buf = (char *)malloc(buf_len + 1); if (my_buf == NULL) { // 内存分配失败的处理 // 可以尝试使用备用方案,比如输出到备用缓冲区或直接返回 return; } // 3. 复制字符串 strncpy(my_buf, buf, buf_len); my_buf[buf_len] = '\0'; // 确保字符串终止 // 4. 移除末尾的换行符 if (buf_len > 0 && my_buf[buf_len - 1] == '\n') { my_buf[buf_len - 1] = '\0'; buf_len--; // 更新长度 // 如果倒数第二个字符是 '\r'(Windows风格换行),也移除 if (buf_len > 0 && my_buf[buf_len - 1] == '\r') { my_buf[buf_len - 1] = '\0'; buf_len--; } } switch (level) { case LV_LOG_LEVEL_WARN: /* code */ ESP_LOGW(TAG, "%s", my_buf); break; case LV_LOG_LEVEL_ERROR: /* code */ ESP_LOGE(TAG, "%s", my_buf); break; default: ESP_LOGI(TAG, "%s", my_buf); break; } // 6. 释放动态分配的内存 free(my_buf); } void lv_log_to_esp_init() { //lv_log_register_print_cb(my_print); }