我自己想出了答案,但花了太长时间。 (我是 arduino 和 C++ 新手)。
问题: 我如何使用像
F("long string to store in flash memory instead of RAM")
(__FlashStringHelper
)这样的字符串,就好像它只是像"normal string"
(const char*
)这样的字符串。
例如
void doSomethingWithText(const char *text) {
char* buffer[17];
strncpy(buffer, text, 16);
Serial.println(buffer);
}
在哪里
doSomethingWithText("Use this text"); // WORKS
doSomethingWithText(F("Use this text instead"); // RAISES COMPILE ERROR
编译错误:
'const __FlashStringHelper*' 参数 1 的已知转换 到 'const char*'
注意:我知道这个问题类似于(How can I compare __FlashStringHelper* with char* on Arduino?),但是当我只是想知道问题的答案时,我花了很长时间才遇到以上。
为了使该函数也适用于
F("...")
,请添加一个以 const __FlashStringHelper*
作为参数的函数重载。例如
// This one stays the same
void doSomethingWithText(const char *text) {
char* buffer[17];
strncpy(buffer, text, 16);
Serial.println(buffer);
}
// This will be used in the case where the argument is F("....")
void doSomethingWithText(const __FlashStringHelper *text) {
char* buffer[17];
strncpy_P(buffer, (const char*)text, 16); // _P is the version to read from program space
Serial.println(buffer);
}
三个关键部分是:重载函数以考虑不同的参数类型,使用各种字符串函数的
_P
版本,将__FlashStringHelper
转换回const char*
。
注意:对于这种简单的情况,
text
可以直接传递给 Serial.println(text)
。
buffer定义有误。明星过剩
char* buffer[17];
// This one stays the same
void doSomethingWithText(const char *text) {
char buffer[17];
strncpy(buffer, text, 16);
Serial.println(buffer);
}
// This will be used in the case where the argument is F("....")
void doSomethingWithText(const __FlashStringHelper *text) {
char buffer[17];
strncpy_P(buffer, (const char*)text, 16); // _P is the version to read from program space
Serial.println(buffer);
}