c/c++语言开发共享将c ++ lambda传递给旧的c函数指针

我必须为旧的c库创建一个c ++包装器。

在类方法中,我必须调用ac函数,它接受其他东西也是函数指针(它是一个事件处理程序,该函数接受一个事件发生时触发的函数)。

一个简单的例子是:

void myclass::add_handler(std::function handler, otherstuff...) { /* * Many things. */ type_of_function_pointer_accepted_by_old_c_library_add_handler nameofvariable = [handler](same_arguments_as_in_definition_of_the_old_c_function_pointer_accepted) { /* * Many other things with other stuff to be done before the * handler but always only when fired and not when myclass::add_handler is called. */ handler(); }; old_c_library_add_handler(nameofvariable); /* * Last things. */ } 

据我所知,编译器抱怨我无法将带有捕获的lambda分配给旧的c函数指针。 问题是:我该怎么做才能解决?

    这是一个例子。 我们使用的事实是,根据C ++标准,不捕获任何内容的lambda可用作函数指针。

     /* The definition of the C function */ typedef void (*PointerToFunction)(); void old_c_function(PointerToFunction handler, void* context); /* An example of a C++ function that calls the above C function */ void Foo(std::function handler) { auto lambda = [] (void* context) { auto handler = reinterpret_cast*>(context); (*handler)(); }; old_c_function(&lambda, &handler); } 

    我相信你可以在你的上下文中使用相同的想法。

      以上就是c/c++开发分享将c ++ lambda传递给旧的c函数指针相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/560007.html

      (0)
      上一篇 2021年1月27日
      下一篇 2021年1月27日

      精彩推荐