Iamafox Iamafox - 2 months ago 5
C Question

How to determine the length of a char * for a generice logger function?

i am writing a reusable logging module for a firmware prototype. I have a logger api which has a wrapper function

void LogWithNum(eLogSubSystem sys, eLogLevel level, char * msg, int * number)


In this wrapper function, a system specific write function is called. Could be UART for example, or a display driver...

All system write / transmit functions somehow require the length in bytes of a message though. And my wrapper function only gets a a char * to the message it should send. See here for example, where my wrapper calls the systems UART transmit function:

void LogWithNum(eLogSubSystem sys, eLogLevel level, char * msg, int * number)
{

UARTDRV_Transmit(handle, char * msg, int msglen);
}


How can i derive the length of any message so i can pass it properly to the underlying transmitting function?

I dont want to use large librarys since i am on a uC and want to save space.

LPs LPs
Answer

Different ways to solve your problem:

Using strlen to calculate the length

void LogWithNum(eLogSubSystem sys, eLogLevel level, char * msg, int * number)
{
     UARTDRV_Transmit(handle, msg, strlen(msg));
}

Or looping through the until null terminator

void LogWithNum(eLogSubSystem sys, eLogLevel level, char * msg, int * number)
{
     while (*msg != '\0')
        UARTDRV_Transmit(handle, msg++, 1);
}

Or calculate the msg length without strlen combining solutions above

void LogWithNum(eLogSubSystem sys, eLogLevel level, char * msg, int * number)
{
     int msg_length = 0;

     while (*msg++ != '\0')
        msg_length++;

     if (msg_length > 0)
        UARTDRV_Transmit(handle, msg, msg_length);
}
Comments