简体   繁体   English

C 中的回调函数没有 printf

[英]Callback function in C does not printf

I'm trying out callback functions in C, and I'm not sure why, but for some reason printf does not work in the callback function.我正在尝试 C 中的回调函数,但我不确定为什么,但出于某种原因 printf 在回调函数中不起作用。 For example:例如:

#include <stdio.h>

void call_this_method()
{
    printf("call_this_method called\n");
}
void callback(void (*method))
{
    printf("callback called\n");
    (void) method;
}

int main(int argc, const char * argv[])
{
    callback(call_this_method);
}

if I try to run this, only "callback called" gets printed out in the console;如果我尝试运行它,只有“回调调用”会在控制台中打印出来; "call_this_method called" does not get printed out. “call_this_method called”不会被打印出来。 Why is that?这是为什么?

First of all void (*method) is a plain pointer to anything .首先void (*method)是一个指向任何东西的普通指针。 It's equal to void *method .它等于void *method You should declare it as a pointer to a function void (*method)(void) .您应该将其声明为指向函数void (*method)(void)的指针。

Secondly, (void) method doesn't call anything.其次, (void) method不调用任何东西。 It just evaluates method as a value on its own, and the discards that value (due to the cast).它只是将method评估为自己的值,然后丢弃该值(由于强制转换)。 With the above fix you call it like any other function:通过上述修复,您可以像调用任何其他函数一样调用它:

method();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM