本文介绍了在C库上使用std :: function的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有以下签名的C库函数

I have a C library function with the following signature,

void register_callback(void (*callback)(int, void*), void* args);

如果有回调的形式,最好的方法是使用它

What is the best way to get this to work with, if I have a callback of the form,

std::function<void(int)>?


推荐答案

std::function<void(int)> bob;
register_callback( [](int x, void* pbob){
  auto& bob = *static_cast<std::function<void(int)>*>(pbob);
  bob(x);
}, &bob );

这在变量 bob

this remains valid for as long as the variable bob does.

bob 的副本是不够的,的实际实例我们在 register_callback 调用中指向的bob 必须生存足够长的时间。

A copy of bob is not enough, the actual instance of bob that we took a pointer to in the register_callback call has to live long enough.

如果这很困难,请考虑使用智能指针包装 std :: function 并指向存储的 std :: function

If this is difficult, consider a smart pointer wrapping said std::function and doing a pointer to the stored std::function.

上面会有适度的开销,因为我们先分配了一个函数指针,然后分配了一个vtable,再分配到 std :: function

There will be modest overhead in the above, in that we dispatch over a function pointer, then over the equivalent of a vtable, then inside the std::function again.

上面发生的事情是我制作了一个无状态的lambda来转换 void * args 指向指向 std :: function 的指针,然后调用该 std ::函数 int 。无状态Lambda可以隐式转换为函数指针。

What is going on above is that I make a stateless lambda to convert the void* args into a pointer-to-std::function, and invoke that std::function with the int. Stateless lambdas can convert to function pointers implicitly.

这篇关于在C库上使用std :: function的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 12:37