C怎么可能没有内部函数,但用C实现的语言可以吗?
发布时间:2020-12-16 10:14:36 所属栏目:百科 来源:网络整理
导读:我最近一直在编写像Lua这样的脚本语言,并且匿名内部函数的存在让我思考.用C语言实现的语言(如Lua)如何在C语言中具有内部函数,无论您做什么,都无法避免在编译期间必须事先声明函数的事实?这是否意味着在C中,实际上有一种方法可以实现内部函数,而这仅仅是实现
我最近一直在编写像Lua这样的脚本语言,并且匿名内部函数的存在让我思考.用C语言实现的语言(如Lua)如何在C语言中具有内部函数,无论您做什么,都无法避免在编译期间必须事先声明函数的事实?这是否意味着在C中,实际上有一种方法可以实现内部函数,而这仅仅是实现庞大的代码库以使它们成为可能的问题?
例如 void *block = malloc(sizeof(1) * 1024); // somehow // write bytes to this memory address to make it operate // like an inner function? // is that even possible? char (*letterFunct)(int) = ((char (*letterFunct)(int))block; // somehow trick C into thinking this block is a function? printf("%cn",(*letterFunct)(5)); // call it 我缺少的关键概念是如何弥合这一差距,理解为什么某些具有高级功能的语言(类,对象,内部函数,多线程)可以用没有所有这些语言的语言实现? 解决方法
闭包和内部函数通常涉及将一个额外的(隐藏)参数传递给保存闭包环境的函数.在C中,您没有那些隐藏的额外参数,因此要在C中实现闭包或内部函数,您需要使这些额外的参数显式化.因此,要在C中实现“内部函数”,您最终可能会得到类似的结果:
struct shared_locals { // locals of function shared with inner function }; int inner_function(struct shared_locals *sl,/* other args to inner function */...) { // code for the inner function -- shared locals accessed va sl } int function(...) { struct shared_locals sl; // the shared locals // call inner function directly inner_function(&sl,...); // pass inner function as a callback func_with_callback(inner_function,&sl); } 上面这类代码是为什么C代码中的’回调’通常涉及函数指针和传递给回调的额外void *参数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |