【问题标题】:Get called function name as string以字符串形式获取调用函数名
【发布时间】:2013-03-20 17:27:36
【问题描述】:

我想显示我正在调用的函数的名称。这是我的代码

void (*tabFtPtr [nbExo])(); // Array of function pointers
int i;
for (i = 0; i < nbExo; ++i)
{
    printf ("%d - %s", i, __function__);
}

我以__function__ 为例,因为它与我想要的非常接近,但我想显示tabFtPtr [nbExo] 指向的函数的名称。

谢谢你帮助我:)

【问题讨论】:

  • 没有标准的做法。你用的是哪个编译器?
  • 如何从 C stackoverflow.com/questions/351134/… 中的函数指针获取函数名
  • 感谢您的快速解答! @zzk,这个话题会很有用,但它不是可移植的:s 我会想另一种方式来做到这一点......
  • 投票重新打开,因为提议的副本没有提及如何在标准 C 中正确执行此操作,__func__

标签: c


【解决方案1】:

您需要遵循 C99 标准或更高版本的 C 编译器。有一个名为 __func__ 的预定义标识符可以满足您的要求。

void func (void)
{
  printf("%s", __func__);
}

编辑:

作为一个奇怪的参考,C 标准 6.4.2.2 规定上述内容与您明确编写的内容完全相同:

void func (void)
{
  static const char f [] = "func"; // where func is the function's name
  printf("%s", f);
}

编辑 2:

因此,要通过函数指针获取名称,您可以构造如下内容:

const char* func (bool whoami, ...)
{
  const char* result;

  if(whoami)
  {
    result = __func__;
  }
  else
  {
    do_work();
    result = NULL;
  }

  return result;
}

int main()
{
  typedef const char*(*func_t)(bool x, ...); 
  func_t function [N] = ...; // array of func pointers

  for(int i=0; i<N; i++)
  {
    printf("%s", function[i](true, ...);
  }
}

【讨论】:

  • 你不能从函数指针中得到那个字符串,对吗?
  • @CarlNorum 只需调用该函数。该函数必须以某种方式集成 func 标识符。
  • 我真的不明白这如何与 OP 的问题相结合,仅此而已。他似乎不想调用这些函数,只是在运行时获取它们的名称。
  • @CarlNorum 我会添加一个例子。
  • 很抱歉回答迟了。它按照我现在想要的方式工作,完美! :) 非常感谢
【解决方案2】:

我不确定这是你想要的,但你可以这样做。声明一个结构来保存函数名称和地址,以及文件范围内的函数数组:

#define FNUM 3

struct fnc {
    void *addr;
    char name[32];
};

void (*f[FNUM])();
struct fnc fnames[FNUM];

在你的代码中通过函数名手动初始化这些,例如

    fnames[0] = (struct fnc){foo1, "foo1"}; // function address + its name
    fnames[1] = (struct fnc){foo2, "foo2"};
    fnames[2] = (struct fnc){foo3, "foo3"};

创建一个函数来搜索数组,例如

char *getfname(void *p)
{
        for (int i = 0; i < FNUM; i++) {
                if (fnames[i].addr == p)
                        return fnames[i].name;
        }
        return NULL;
}

我对此进行了快速测试。我在main 中初始化了数组,并调用了foo1()。这是我的函数和输出:

void foo1(void)
{
    printf("The pointer of the current function is %p\n", getfnp(__func__));
    printf("The name of this function is %s\n", getfname(getfnp(__func__)));
    printf("The name of the function at pointer f[2] (%p) is '%s'\n", f[2],
        getfname(f[2]));    
}

The pointer of the current function is 0x400715
The name of this function is foo1
The name of the function at pointer f[2] (0x40078c) is 'foo3'

或者,更一般地说:

void foo2(void)
{
    for (int i = 0; i < FNUM; i++) {
        printf("Function f[%d] is called '%s'\n", i, getfname(f[i]));
    }
}

Function f[0] is called 'foo1'
Function f[1] is called 'foo2'
Function f[2] is called 'foo3'

【讨论】:

  • 为了提高性能,这可能是一个更好的解决方案,因为它不会给函数增加额外的开销。
猜你喜欢
  • 2014-05-23
  • 2015-03-18
  • 2013-08-20
  • 2021-02-25
  • 1970-01-01
  • 2011-09-30
  • 1970-01-01
相关资源
最近更新 更多