C 中的假匿名函数 [英] Fake anonymous functions in C

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

问题描述

这个SO线程中,Brian Postow 建议一个涉及假匿名函数的解决方案:

In this SO thread, Brian Postow suggested a solution involving fake anonymous functions:

创建一个 comp(L) 函数,该函数返回长度为 L 的数组的 comp 版本...这样 L 就成为一个参数,而不是一个全局变量

make a comp(L) function that returns the version of comp for arrays of length L... that way L becomes a parameter, not a global

如何实现这样的功能?

推荐答案

参见 我刚刚发布到那个问题的答案.您可以使用 callback(3) 库在运行时生成新函数.它不符合标准,因为它涉及许多丑陋的特定于平台的黑客攻击,但它确实适用于大量系统.

See the answer I just posted to that question. You can use the callback(3) library to generate new functions at runtime. It's not standards compliant, since it involves lots of ugly platform-specific hacks, but it does work on a large number of systems.

该库负责分配内存,确保内存是可执行的,并在必要时刷新指令缓存,以确保动态生成的代码(即闭包)是可执行的.它本质上会生成在 x86 上看起来像这样的代码存根:

The library takes care of allocating memory, making sure that memory is executable, and flushing the instruction cache if necessary, in order to ensure that code which is dynamically generated (i.e. the closure) is executable. It essentially generates stubs of code that might look like this on x86:

  pop %ecx
  push $THUNK
  push %ecx
  jmp $function
THUNK:
  .long $parameter

然后返回第一条指令的地址.这个存根的作用是将返回地址存储到 ECX(x86 调用约定中的临时寄存器)中,将一个额外的参数压入堆栈(一个指向 thunk 的指针),然后重新压入返回地址.然后,它跳转到实际的函数.这导致函数被愚弄,认为它有一个额外的参数,即闭包的隐藏上下文.

And then returns the address of the first instruction. What this stub does is stores the the return address into ECX (a scratch register in the x86 calling convention), pushes an extra parameter onto the stack (a pointer to a thunk), and then re-pushes the return address. Then, it jumps to the actual function. This results in the function getting fooled into thinking it has an extra parameter, which is the hidden context of the closure.

实际上比那个更复杂(存根末尾调用的实际函数是__vacall_r,而不是函数本身,__vacall_r()处理更多的实现细节),但这是基本原则.

It's actually more complicated than that (the actual function called at the end of the stub is __vacall_r, not the function itself, and __vacall_r() handles more implementation details), but that's the basic principle.

这篇关于C 中的假匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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