将void指针传递给函数指针

时间:2013-02-13 03:07:08

标签: c function-pointers void-pointers

简而言之,我试图使用void指针作为函数指针的参数,但是我得到编译器错误“无效使用void表达式”。

我有一个双向链表(DLL),其节点结构如下:

typedef struct DL_LIST
{
    uint16 tag;                 /* Object ID tag */
    struct DL_LIST *previous;
    struct DL_LIST *next;
    void *object;               /* A pointer to this node's object */
    uint32 size;                /* The size of this node's object, in bytes */
} DL_LIST;

我还有以下用于删除单个节点的函数:

void dl_delete(DL_LIST *node, void (*dl_destructor)(void*)) {
    if (node != NULL) {
        dl_extract(node);       /* Removes the node from the list */

        if (node->object != NULL) {
            (*dl_destructor)(node->object);

            free(node->object);
        }

        free(node);
    }
}

节点提取功能是:

DL_LIST *dl_extract(DL_LIST *node) {
    if (node != NULL) {
        if (node->previous != NULL) {
            node->previous->next = node->next;
        }

        if (node->next != NULL) {
            node->next->previous = node->previous;
        }

        node->previous = NULL;
        node->next = NULL;
    }

    return node;
}

这里的想法是能够为可能存储在节点中的每种object类型传递单独的析构函数。此析构函数将指向对象的指针作为参数,并用于释放object的子项正在使用的任何堆内存。

当我尝试从用于删除整个DLL的函数调用dl_delete()时,会出现上述错误:

void dl_destroy(DL_LIST **list, void (*dl_destructor)(void*)) {
    DL_LIST *marker;
    DL_LIST *previous_node;

    if (*list != NULL) {
        previous_node = (*list)->previous;

        while (previous_node != NULL) {
            marker = previous_node->previous;
            dl_delete(previous_node, (*dl_destructor)(previous_node->object));
            previous_node = marker;
        }

        /* Code removed for brevity */
    }
}

我已阅读this函数指针的介绍,但仍无法确定如何解决问题。我非常感激地解释我做错了什么。

1 个答案:

答案 0 :(得分:3)

这一行

dl_delete(previous_node, (*dl_destructor)(previous_node->object));

需要dl_delete(previous_node, dl_destructor);

也在dl_delete这一行(*dl_destructor)(node->object);

应为dl_destructor(node->object);

另外,为了安全起见,我想在尝试使用它们进行调用之前检查我的函数指针是否为空

所以在dl_delete中就像: -

if(dl_destructor!=NULL) dl_destructor(node->object);