在 Arduino 上使用 C 中 PROGMEM 中的结构函数指针
Using Function Pointer from struct in PROGMEM in C on Arduino
我试图从存储在 PROGMEM 中的结构中读取一个函数指针,然后将一个值(输入)传递给相应的函数并保存返回值,但我找不到正确的语法。
uint8_t (*pStateFunc) (uint8_t);
uint8_t input;
uint8_t nextstate;
enum MENUSTATES {STATE1, STATE2};
typedef struct PROGMEM {
unsigned char state;
uint16_t someNumber; // Just arbitrary information
uint8_t (*pFunc) (uint8_t input);
} MENU_STATE;
const MENU_STATE menu_state[] PROGMEM = {
// state someNumber pFunc
{STATE1, 2, NULL},
{STATE2, 4, doSomething},
{0, 0, NULL}
};
// Get the Function
pStateFunc = (PGM_VOID_P) pgm_read_byte(&menu_state[1].pFunc);
// Execute the Function and save the returned state
nextstate = pStateFunc(input);
// Function Definition
uint8_t doSomething(u8int_t input){
return STATE1;
}
我得到的只是来自 Arduino IDE 1.6.5 的以下错误:
invalid conversion from 'const void*' to 'uint8_t (*)(uint8_t) {aka unsigned char (*)(unsigned char)}' [-fpermissive]
如何从 PROGMEM 中读取函数并正确执行它?
您似乎正在读取一个字节 - 我原以为 pgm_read_ptr
会更合适。
您需要将其转换为正确的类型:
typedef uint8_t (*StateFunc) (uint8_t);
pStateFunc = (StateFunc) pgm_read_ptr(&menu_state[1].pFunc);
我试图从存储在 PROGMEM 中的结构中读取一个函数指针,然后将一个值(输入)传递给相应的函数并保存返回值,但我找不到正确的语法。
uint8_t (*pStateFunc) (uint8_t);
uint8_t input;
uint8_t nextstate;
enum MENUSTATES {STATE1, STATE2};
typedef struct PROGMEM {
unsigned char state;
uint16_t someNumber; // Just arbitrary information
uint8_t (*pFunc) (uint8_t input);
} MENU_STATE;
const MENU_STATE menu_state[] PROGMEM = {
// state someNumber pFunc
{STATE1, 2, NULL},
{STATE2, 4, doSomething},
{0, 0, NULL}
};
// Get the Function
pStateFunc = (PGM_VOID_P) pgm_read_byte(&menu_state[1].pFunc);
// Execute the Function and save the returned state
nextstate = pStateFunc(input);
// Function Definition
uint8_t doSomething(u8int_t input){
return STATE1;
}
我得到的只是来自 Arduino IDE 1.6.5 的以下错误:
invalid conversion from 'const void*' to 'uint8_t (*)(uint8_t) {aka unsigned char (*)(unsigned char)}' [-fpermissive]
如何从 PROGMEM 中读取函数并正确执行它?
您似乎正在读取一个字节 - 我原以为 pgm_read_ptr
会更合适。
您需要将其转换为正确的类型:
typedef uint8_t (*StateFunc) (uint8_t);
pStateFunc = (StateFunc) pgm_read_ptr(&menu_state[1].pFunc);