调用void*指针指向的函数

TSM*_*TSM 4 c pointers

我有一个看起来像这样的事件结构

typedef struct {
    void* fn;
    void* param;
} event;
Run Code Online (Sandbox Code Playgroud)

如何通过指针作为结构的一部分来调用此函数.例如,这些不起作用:

event->(*function)();
event->function();
(*event->function)();
Run Code Online (Sandbox Code Playgroud)

我想知道如何使用和不使用额外的void*param进行函数调用.我最初使用此链接作为参考:

http://www.cprogramming.com/tutorial/function-pointers.html

我之前使用过这些函数指针,但是无法正确获取语法.

Nem*_*ric 6

您需要首先将void*指针强制转换为函数指针:

#include <stdio.h>

typedef struct {
    void* fn;
    void* param;
} event;

void print()
{
        printf("Hello\n");
}


int main()
{
    event e;
        e.fn = print;
        ((void(*)())e.fn)();
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

当然,如果这真的是你想要的.如果希望结构包含指向函数的void*指针而不是指针,请在声明中使用正确的类型:

typedef struct {
    void (*fn)();
    void* param;
} event;
Run Code Online (Sandbox Code Playgroud)

在这里,您已fn声明为指向void函数的指针和paramas void*指针.