将成员函数指针传递给 C 风格的函数

Passing member function pointer to the c-style function

我正在尝试将成员函数指针传递给 C 风格的函数(因为它是 C 中的库)

它要的指针定义为:

void (*)(int, const char*)

所以我要传递的函数是:

void Application::onError(int error, const char *description)

我正在尝试使用此代码传递它:

setCallback(bind(&Game::onError, this, placeholders::_1, placeholders::_2));

这给了我以下错误:

cannot convert ‘std::_Bind_helper<false, void (Application::*)(Application*, int,
const char*), Application* const, const std::_Placeholder<1>&, const 
std::_Placeholder<2>&>::type {aka std::_Bind<std::_Mem_fn<void (Application::*)
(Application*, int, const char*)>(Application*, std::_Placeholder<1>,
std::_Placeholder<2>)>}’ to ‘GLFWerrorfun {aka void (*)(int, const char*)}’ for 
argument ‘1’ to ‘void (* glfwSetErrorCallback(GLFWerrorfun))(int, const char*)’
glfwSetErrorCallback(bind(&Application::onError, this, placeholders::_1, placeholders::_2));

有什么方法可以成功地将成员函数作为绑定函数传递给 c 风格的函数吗?

不直接,不。 C++ 成员函数需要一个隐式 this 指针,当然 C 不知道也不会传递。

解决这个问题的通常方法是引入 "trampoline" 作为 class 方法,但也许在更现代的 C++ 变体中有更漂亮的方法。

std::bind 的结果是一个复杂的 C++ 对象。例如,它必须存储所有绑定参数。所以它绝对不能转换为指向函数的指针。

您正在处理的回调规范显然不允许 "user data" 有效负载,因此没有地方可以隐藏指向 C++ 对象的指针,您可以使用它来调用非静态成员函数。这意味着您将不得不调用全局或静态成员函数,或求助于 global/static member/per-thread 变量来存储对象指针。

唯一 100% 可移植的方法是创建一个 C 链接函数用作回调。这样做,并使用全局对象指针来调用您原来的 onError():

Application *error_handling_application;

extern "C" void errorCallback(int error, const char *description)
{
  error_handling_application->onError(error, description);
}

请注意,您经常会遇到使用静态成员函数代替我的 errorCallback 的程序。这适用于大多数平台上的大多数编译器,但不保证 工作。 C 库需要一个具有 C 语言链接的函数。静态成员函数只能有 C++ 语言链接。 C 函数和 C++ 函数的调用机制可能不同(取决于 ABI),这将导致对传入的静态成员函数的格式错误调用。

由于成员函数也有 this 指针作为隐含参数,它不是 C 函数接受的类型。因此,恕我直言,唯一的方法是生成一个带有 C linkage

的独立函数
class A {
public: void func(int, const char*) const;
};

extern "C" {
  void cfunc(void(*)(int, const char*));
  void call_cfunc(const A*);
}

// in some source (non-header) file:
namespace {
  const A*pa;
  void afunc(int i, const char*s)
  { pa->func(i,s); }
}

void call_cfunc(const A*a)
{
  pa = a;
  cfunc(afunc);
}