没有名称的功能

时间:2018-09-03 14:06:49

标签: c++ function function-pointers

我想知道如何调用此函数?如果没有名称,我在哪里可以找到它的实现?

extern void (*_malloc_message)(const char* p1, const char* p2, const char* p3, const char* p4);

3 个答案:

答案 0 :(得分:22)

这不是功能。声明是说_malloc_message是一个指向函数的指针,返回类型为void,参数如给定。

要使用它,您必须为其分配具有该属性,返回类型和参数类型的函数的地址

然后您将_malloc_message当作函数使用。

答案 1 :(得分:3)

_malloc_message是一个函数指针。

在代码中的某个地方,您会找到一个函数的定义,该函数的原型如下:

void foo (const char* p1, const char* p2, const char* p3, const char* p4);

然后将函数分配给函数指针,如下所示:

_malloc_message = foo;

并这样称呼它:

(*_malloc_message)(p1, p2, p3, p4);

问题是为什么您不能直接调用foo。 原因之一是您知道仅在运行时才需要调用foo。

答案 2 :(得分:0)

_malloc_message在jemalloc的malloc.c中定义:

这是您的使用方式:

extern void malloc_error_logger(const char *p1, const char *p2, const char *p3, const char *p4)
{
    syslog(LOG_ERR, "malloc error: %s %s %s %s", p1, p2, p3, p4);
}

//extern
_malloc_message = malloc_error_logger;

malloc_error_logger()将在各种malloc库错误中被调用。 malloc.c有更多详细信息。