我目前正在为微处理器编写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;
}
我在上面包含了函数exec_command
,这是使用函数指针的地方。在底部,我也放了start_simulation
和stop_simulation
函数,以及CmdLed
。我在早些时候写了CmdLed
,然后回来写了start_simulation
和stop_simulation
。我忘记了我已经将函数指针定义为将(char *)
作为参数。然而,我惊讶地发现一切仍然编译和运行得非常好。为什么会这样?似乎任何参数都只是"转储"而不使用。
不能用现代编译器编译。
这里发生了什么:
start_simulation
将带char*
参数调用,但由于start_simulation
没有参数,该参数被简单地忽略(或者在您编写时"转储")。
请记住,在C函数中,参数被压入堆栈,调用者在调用后清理堆栈。所以如果你调用一个没有参数的函数假装它有参数,那么
- 调用者将参数压入堆栈
- 无参数函数被调用者调用
- 函数忽略栈上的参数
- 函数返回给调用者
- 调用者清理堆栈
再看看这个SO问题
我假设你在使用它们之前已经声明了你的函数,或者你的编译器隐式地声明了它们(C默认):
int start_simulation();
...
意味着start_simulation
应该在其他地方定义为接受任何形参并返回int的函数。
但是这至少应该给你一些警告,因为要么定义与声明不同,要么函数的声明与命令结构的第二个元素的命令声明不匹配(在const commandStruct commands[] = ...
中)
由于编译和运行良好,cdecl传递参数的方式如下:
- 参数以相反的顺序被压入堆栈
- 被调用者被调用(调用者的返回地址被推送到堆栈)
- 被调用者可以从堆栈指针+返回地址的大小开始获取其参数,但永远不会从堆栈中删除它们
- 被返回
- 调用者移除它推送到堆栈的参数(它知道这些参数)
这意味着你总是可以添加未使用的参数,前提是编译器能够容忍编译错误的调用,或者函数是用空参数列表声明的。