S1i*_*ery 5 c function-pointers
我目前正在为微处理器编写 C 代码,我遇到了一些我无法解释的事情。我已经使用函数指针实现了命令行界面。为此,我创建了一个结构体,其中包含命令的名称、指向要运行的函数的指针以及帮助说明。
typedef void(*command)(char *);
typedef struct commandStruct {
char const *name;
command execute;
char const *help;
} commandStruct;
const commandStruct commands[] =
{
{"led", CmdLed, "Turns on or off the LED1"},
{"AT+START_SIM", start_simulation, "Starts the simulation"},
{"AT+STOP_SIM", stop_simulation, "Stops the simulation"},
{"",0,""} //End of table indicator.
};
void exec_command(char *buffer)
{
uint16 i = 0;
char *cmd = buffer;
char *args;
while (buffer[i])
{
if(buffer[i] == '=')
{
buffer[i] = 0;
args = buffer + i + 1;
break;
}
i++;
}
uint16 cmdCount = 0;
while(strcmp(commands[cmdCount].name,""))
{
if(!strcmp(commands[cmdCount].name,cmd))
{
commands[cmdCount].execute(args);
break;
}
cmdCount++;
}
}
void start_simulation(void) {run = 1;}
void stop_simulation(void) {run = 0;}
void CmdLed(char *args)
{
P1DIR |= BIT0;
if(!strcmp(args,"on")) P1OUT = 1;
if(!strcmp(args,"off")) P1OUT = 0;
}
Run Code Online (Sandbox Code Playgroud)
exec_command我已经在上面包含了使用函数指针的函数。在底部我还放置了start_simulation和stop_simulation函数以及CmdLed. 我CmdLed早些时候写过,然后回来写了start_simulation和stop_simulation。我忘记了我已经将函数指针定义为以 a(char *)作为参数。然而,我惊讶地发现一切仍然编译并运行得非常好。为什么是这样?似乎任何参数都只是“转储”而不被使用。