Hello,
I have a function where one of the argument is a pointer to a text string in PROGMEM. The function need to find the length of the test string. I search and found that some have used strlen_P. But this seem to give me an error while compiling the sketch:
int readValue(const int line, const __FlashStringHelper *text, const int digits)
{
int val = 0;
lcd1.writeLine(line, text);
val = readNumber(digits, 1 + strlen_P(text));
return val;
}
void someFunc()
{
int val = readValue(1, F("Enter number:"), 2);
}
The error I get is:
cannot convert 'const __FlashStringHelper*' to 'const char*' for argument '1' to 'size_t strlen_P(const char*)'
What do I do wrong?
strlen_P() takes a 'const char *' argument, not a 'const __FlashStringHelper *'
strlen_P(reinterpret_cast<const char *>(text))
Reinterpret_cast is dangerous, and can only be used in a very limited number of cases: reinterpret_cast conversion - cppreference.com
In this case, it's valid, because the underlying type of a progmem string actually is const char *. The F(...) macro reinterpret_casts it to a pointer to an incomplete helper type __FlashStringHelper. It does this to get the correct overload resolution for functions like Serial.print. The link I mentioned earlier explains that it's safe to cast it back to the original type in that case (and that's pretty much the only thing you can do with it).
F macro definition
Pieter
Thanks. I did not thought about using reinterpret_cast.