PROGMEM はそれほど使いやすいものではありません。そして、少し単純化することができます:
#include <avr/pgmspace.h>
struct Route {
void (*func)();
const char *URI;
};
void test1() {
Serial.println(F("Executed testfunc1")); // if you are using progmem, why not for string literals?
}
void test2() {
Serial.println(F("Executed testfunc2"));
}
const char route1URI[] PROGMEM = "/route1";
const char route2URI[] PROGMEM = "/route2";
const Route routingTable[] PROGMEM = {
{test1,route1URI},
{test2,route2URI}
};
void (*getRoute(char *URI))() {
Route r;
memcpy_P((void*)&r, routingTable, sizeof(r)); // read flash memory into the r space. (can be done by constructor too)
Serial.println((__FlashStringHelper*)r.URI); // it'll use progmem based print
// for comparing use: strcmp_P( URI, r.URI)
return r.func; // r.func is already pointer to the function
}
void setup() {
Serial.begin(57600);
while (!Serial) { }
Serial.println("started setup");
void (*fn)() = getRoute("sometest");
// will cause errors if called
//fn();
Serial.print((uint16_t)test1, HEX); Serial.print(' ');
Serial.print((uint16_t)test2, HEX); Serial.print(' ');
Serial.println((uint16_t)fn, HEX);
Serial.println("ended setup");
}
void loop() {
// put your main code here, to run repeatedly:
}
へのコピーに使用されたため、すべての問題を引き起こす可能性があるroute1
と思います。私が行ったように要素を初期化すると、はるかにうまく機能します。また、たくさん壊れました。route2
routingTable
routingTable
getRoute
とにかく、フラッシュ文字列がある場合は、String str {(__FlashStringHelper*)r.URI};
比較演算子も使用してから使用できます: str == URI
:
#include <avr/pgmspace.h>
// get size of array[]
template<typename T, int size> int GetArrLength(T(&)[size]){return size;}
struct Route {
void (*func)();
const char *URI;
};
void test1() {
Serial.println(F("Executed testfunc1")); // if you are using progmem, why not for string literals?
}
void test2() {
Serial.println(F("Executed testfunc2"));
}
void test3() {
Serial.println(F("Executed testfunc3"));
}
const char route1URI[] PROGMEM = "/route1";
const char route2URI[] PROGMEM = "/route2";
const char route3URI[] PROGMEM = "/route3";
const Route routingTable[] PROGMEM = {
{test1,route1URI},
{test2,route2URI},
{test3,route3URI}
};
void (*getRoute(char *URI))() {
for (int8_t i = 0; i < GetArrLength(routingTable); ++i) {
Route r;
memcpy_P((void*)&r, routingTable+i, sizeof(r)); // read flash memory into the r space. (can be done by constructor too)
String uri {(__FlashStringHelper*)r.URI};
if (uri == URI) {
return r.func; // r.func is already pointer to the function
}
}
return nullptr;
}
void setup() {
Serial.begin(57600);
while (!Serial) { }
Serial.println("started setup");
void (*fn)() = getRoute("/route3");
// will cause errors if called
//fn();
Serial.print((uint16_t)test1, HEX); Serial.print(' ');
Serial.print((uint16_t)test2, HEX); Serial.print(' ');
Serial.print((uint16_t)test3, HEX); Serial.print(' ');
Serial.println((uint16_t)fn, HEX);
Serial.println("ended setup");
}