通过一个C ++ lambda来旧的C函数指针 [英] Pass a c++ lambda to old c function pointer

查看:167
本文介绍了通过一个C ++ lambda来旧的C函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一个C ++包装到一个旧的C库。

I have to create a c++ wrapper to a old c library.

在一个类的方法,我必须调用C函数,与其他的东西也是一个函数指针(这是一个事件处理程序和函数使用时,事件发生时被触发的函数)。

In a class method I must call a c function that takes with other stuff also a function pointer(it is a event handler and the function takes a function that is fired when a event happens).

它的一个简单的例子是这样的:

A simple example of it is this:

void myclass::add_handler(std::function<void()> 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函数指针。
现在的问题是:我该怎么做才能解决。

The compiler complains, as I know, that I can't assign a lambda with capture to an old c function pointer. The question is: how can I do to solve?

推荐答案

下面是一个例子。我们使用的事实,没有捕获任何lambda表达式的,根据C ++标准,可作为函数指针。

Here is an example. We are using the fact that lambdas that do not capture anything are, according to the C++ standard, usable as function pointers.

/* 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<void()> handler)
{
    auto lambda = [] (void* context) {
        auto handler = reinterpret_cast<std::function<void()>*>(context);
        (*handler)();
    };

    old_c_function(&lambda, &handler); 
}

我相信你可以使用同样的想法在你的环境。

I believe you can use the same idea in your context.

这篇关于通过一个C ++ lambda来旧的C函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆