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

How to create a function that returns another function, encompassing a given argument implicitly in C?

我想要一个函数 returns 一个在 没有参数的情况下被调用的函数 ,即使原始函数必须被调用 一个参数。参数传递给第一个函数,每次调用返回的函数时都会隐式使用。

我知道 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()

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

你在 C 语言中所能做的就是创建一个包含函数指针和要传递的参数的记录(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);
}

输出:

Called A(34).
Called B(79).