在函数调用中将函数指针转换为 void*,然后将它们重新转换为原始类型

问题描述 投票:0回答:1

我有一个包含函数回调的结构,该函数回调的定义因编译器而异

typedef struct structA
{
#ifdef _compilerA_
  void (*func) (int);
  int param;
#else
  void (func) (unionA);
  unionA param;
#endif
}

并且 unionA 定义为

typedef union unionA
{
  int num;
}

现在我有一个接口,最初采用 void(*fp)(int),然后将本地函数指针设置为 fp,但由于取决于编译器的 fp 类型不同,我必须设置它如下

void interfaceB(void *fp, int param)
{
  structA local;
#ifdef _compilerA_
  local->func = reinterpret_cast<void(*)(int)>(fp);
  local->param = param;
#else
  local->func = reinterpret_cast<void(*)(unionA)>(fp);
  unionA param_unionA;
  param_unionA.num = param;
  local->param = param_unionA;
}

当我将函数回调传递给函数 A 并尝试将其转换为 void* 时,就会出现问题。假设我有一个函数回调

void callbackC (int param)

当我尝试将其转换为 void* 到 interfaceB 时,我遇到了编译器问题

interfaceB(reinterpret_cast<void*>(callbackC)

错误消息是无法将函数从类型

void(*)(int)
转换为类型
void*
。我该如何解决这个问题?谢谢你。

c++ compiler-errors casting type-conversion compiler-warnings
1个回答
0
投票

为什么不将类型定义向上移动并根据编译器重新定义参数类型?

#ifdef _compilerA_
typedef int FuncArg;
inline FuncArg funcArgFromInt(int const x) { return x; }
#else
typedef unionA FuncArg;
inline FuncArg funcArgFromInt(int const x) {
  unionA param_unionA;
  param_unionA.num = x;
  return param_unionA;
}
#endif
typedef void (*FuncPtr)(FuncArg);

struct StructA {
  FuncPtr func;
  FuncArg arg;
};

然后调用就变成:

void interfaceB(FuncPtr const fp, int const param) {
  StructA const local{fp, param};
  // do things with `local`, presumably? E.g.:
  local.fp(funcArgFromInt(local.arg));
}
© www.soinside.com 2019 - 2024. All rights reserved.