[SOLVED] How to correctly pass a font type as a parameter?

Description

I’m trying to pass a font as a parameter to a function, but I get a BUS ERROR

What MCU/Processor/Board and compiler are you using?

Raspberry PI 4B, GCC 8.3.0

What LVGL version are you using?

7.9

What do you want to achieve?

Pass a font as a parameter to a method (example: to draw a label specifying the font and other parameters)

What have you tried so far?

Writing a method which takes lv_font_t as parameter and passing the font, after having declared it with LV_FONT_DECLARE()

Code to reproduce

void drawLabel(const char* sText, const lv_align_t lAlignment, const lv_coord_t lCorrectionX, const lv_coord_t lCorrectionY, lv_font_t textFont, const lv_color_t textColor)
{
	lv_obj_t* pLabel;
	
	pLabel = lv_label_create(lv_scr_act(), NULL);
	lv_label_set_static_text(pLabel, sText);
	lv_obj_set_style_local_text_color(pLabel, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, textColor);
	lv_obj_set_style_local_text_font(pLabel, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, &textFont);
	// NULL = align on parent (the screen)
	lv_obj_align(pLabel, NULL, lAlignment, lCorrectionX, lCorrectionY);
}

static void drawMainLabel(lv_align_t lAlignment, lv_coord_t lCorrectionX, lv_coord_t lCorrectionY)
{   
    LV_FONT_DECLARE(audio_32);
	drawLabel(TITLE_TEXT, lAlignment, lCorrectionX, lCorrectionY, audio_32, LV_COLOR_BLUE);
}

Result: no label is drawn and BUS ERROR occurs

Label is OK (and no BUS ERROR) if drawn without calling drawLabel, for example:

static void drawMainLabel(lv_align_t lAlignment, lv_coord_t lCorrectionX, lv_coord_t lCorrectionY)
{
    lv_obj_t* pLabel;
    LV_FONT_DECLARE(audio_32);

    pLabel = lv_label_create(lv_scr_act(), NULL);
    lv_label_set_static_text(pLabel, TITLE_TEXT);
    lv_obj_set_style_local_text_color(pLabel, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLUE);
    lv_obj_set_style_local_text_font(pLabel, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, &audio_32);

    // NULL = align on parent (the screen)
    lv_obj_align(pLabel, NULL, lAlignment, lCorrectionX, lCorrectionY);
}

There are 2 ways to pass parameters in C, by reference & by value. You are passing by value and taking the address of the local stack variable which goes out of scope at the end the function.

2 Likes

@jupeos is correct; you should pass &audio_32 to the function and change it to take lv_font_t * as a parameter. Right now you are passing the font structure directly, which is not what LVGL expects.

1 Like

D’oh!!
You are right, obviously!!

Thanks!