在C中实现闭包 [英] Achieving Closure in C

查看:92
本文介绍了在C中实现闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我本质上是试图在C中复制C#的Linq功能.

I am essentially trying to replicate C#'s Linq's functionality in C.

在C#中,代码看起来像这样

In C# the code would look like this

// main
Coordinate coord = new Coordinate { x = 0, y = 0};
bool result = coordinates.Any(c => c.Data.Y == coord.Y || c.Data.X == coord.X);

在C语言中,我到此为止:

In C, I have gotten this far:

int any(struct linked_list *list, int (*cb)(struct node *node))
{
    .....
    do
    {
    if (cb)
        if ((*cb)(pNode))
            return 1;
    pNode = pNode->next;
    } while (pNode);
    return 0;
}

int compareCoordinates(struct node *node, struct coordinate *coord)
{
    struct coordinate *iterator = node->data;
    return iterator->x == coord->x || iterator->y == coord->y;
}
// main
struct coordinate coord;
int result = any(coordinates,compareCoordinates(??, coord));

我意识到将两个参数传递给带有一个参数的函数没有多大意义,但是据我所知,在调用该函数之前,参数已添加到堆栈中,因此我认为必须有一种方法可以同时使用这两种方法.我正在学习C娱乐,因此我不确定对Google到底是什么,因为这是我以前从未做过的事情.我认为Linq库是否可以在C#中实现它,那么在C语言中应该可以实现.是否有另一种方法可以从回调中访问局部变量?

I realize that it doesn't make much sense to pass two arguments into a function with one parameter, but from my knowledge, arguments get added to the stack before the function is called, so I figure there must be a way to have access to both.. I'm learning C for fun and I'm not sure exactly what to Google as this is something I've never done before. I figure if the Linq library can make it happen in C#, then it should be possible in C. Is there another way to access local variables from your callback?

经过更多的研究,我意识到我可以用嵌套函数实现我想要的功能,尽管我仍然很想知道是否可以将比签名状态更多的信息传递给函数.

After some more research, I realized I could achieve what I want with nested functions, although I am still curious as to see if you can pass more to a function than the signature states.

推荐答案

您可以从技术上在GNU C中嵌套函数定义(请注意,这不是闭包,因为它不会保持 coord 父函数返回后):

You can technically nest function definitions in GNU C (note that isn't a closure, as it won't keep coord around after the parent function returns):

int main(void) {
  struct coordinate coord;

  int compareCoordinates(struct node *node) {
    ...
  };

  any(list, compareCoordinates);
}

..但是您实际上不应该(非便携式行为).普通的 for 循环更简单,更快,更容易阅读,就像诱骗此类高阶函数的陷阱一样.

..but you really shouldn't (non-portable behavior). A normal for loop is simpler, faster, and easier to read, as tempting as the trappings of such a higher-order function is.

另一方面,在C ++ 11及更高版本中,您可以使用lambda使其更接近原始C#模式:

In C++11 and up, on the other hand, you could get closer to the original C# pattern with a lambda:

any(list, [](struct node *node) -> bool { ... });

这篇关于在C中实现闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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