如何创建一个返回另一个函数的函数,在C中隐式包含给定参数?

Fla*_*bou 2 c closures function-pointers

我希望有一个函数可以返回带参数调用的函数,即使原始函数必须参数调用也是如此。该参数将传递给第一个函数,并且每次调用返回的函数时都将隐式使用该参数。

我知道C中的函数指针,但不知道是否可以这种方式使用它们。我知道如何在python中执行此操作,如以下示例代码所示:

def foo(some_argument):
    print(some_argument)

def register_callback(function, argument):
    def new_function():
        function(argument)

    return new_function

bar = register_callback(foo,"bar")

bar()
Run Code Online (Sandbox Code Playgroud)

据我了解,在C语言中这种方法是不可能的,因为我们不能嵌套函数定义。这是可能的,如果可以的话,这样做的正确方法是什么?

Eri*_*hil 5

在C语言中,您几乎可以做的就是创建一条记录(a struct),其中包含要传递的函数指针和参数,然后在实际执行调用的包装函数的帮助下,将该记录用作被调用的“事物” 。

#include <stdio.h>


typedef int SomeType;   //  Sample type for demonstration.


//  Define a record to hold a function pointer and the argument we want to pass.
typedef struct
{
    void (*Function)(SomeType); //  Function to call.
    SomeType Argument;  //  Argument to pass.
} Closure;


//  Define some sample functions.
static void A(SomeType x) { printf("Called %s(%d).\n", __func__, x); }
static void B(SomeType x) { printf("Called %s(%d).\n", __func__, x); }


//  Define a function that returns a closure.
static Closure foo(int Which, SomeType x)
{
    return (Closure) { .Function = Which & 1 ? B : A, .Argument = x };
}


//  Define a function to call a closure.
static void Call(Closure C) { C.Function(C.Argument); }


int main(void)
{
    Closure a = foo(0, 34);
    Closure b = foo(1, 79);
    Call(a);
    Call(b);
}
Run Code Online (Sandbox Code Playgroud)

输出:

称为A(34)。
称为B(79)。