首先得说明一点,C 语言不是函数式编程语言,要想进行完全的函数式编程,还得先写个虚拟机,然后再写个解释器才行(相当于 CPython )。
下面我们提供一个例子,说明 C 语言函数可以“适度地模仿” Python 函数。
我们有如下的 Python 程序:
def line_conf(a, b):
def line(x):
return a*x + b
return line
line1 = line_conf(1, 1)
line2 = line_conf(4, 5)
print(line1(5), line2(5))
我们在C程序中适度地模拟其中的line_conf函数:
/////////////////////////////////////////////////////////////////////////////// // Note: The C program is almost equivalent to the Python program as follows: // def line_conf(a, b): // def line(x): // return a*x + b // return line // // line1 = line_conf(1, 1) // line2 = line_conf(4, 5) // print(line1(5), line2(5)) #include#include #include #include typedef int Func(); Func *line_conf(int x, int y,...) { va_list ap; va_start(ap, y); asm volatile( "push %%eaxnt" "subl $40, %%espnt" "movl 8(%%ebp), %%eaxnt" "movl %%eax, -36(%%ebp)nt" "movl 12(%%ebp), %%eaxnt" "movl %%eax, -40(%%ebp)nt" "addl $40, %%espnt" "pop %%eaxnt" :::"memory" ); if(va_arg(ap,int) == 1){ LINE: asm volatile( "push %%ebpnt" "movl %%esp, %%ebpnt" "movl 8(%%ebp), %%eaxnt" "imul -36(%%ebp), %%eaxnt" "addl -40(%%ebp), %%eaxnt" "movl %%ebp, %%espnt" "pop %%ebpnt" "retnt" :::"memory","%eax" ); } __END: va_end(ap); return (Func *)(&&LINE); } int main(int argc, const char *argv[]){ printf("====TEST START====n"); printf("34*234+6 ?= %dn",line_conf(34,6)(234)); printf("1*3+2 ?= %d; 324*65+3 ?= %d; 13*66+2 ?= %dn",line_conf(1,2)(3),line_conf(324,3)(65),line_conf(13,2)(66)); int fd = line_conf(1,6)(4); Func *fun = line_conf(3,3); int a = 1; // Limited point printf("3*3+3 ?= %d; 1*4+6 ?= %dn",fun(3),fd); printf("====TEST END====n"); return 0; } // Compile it by the following command: // gcc -m32 -O0 -fno-stack-protector CFunctional.c; ./a.out // The terminal output should looks like: // ====TEST START==== // 34*234+6 ?= 7962 // 1*3+2 ?= 5; 324*65+3 ?= 21063; 13*66+2 ?= 860 // 3*3+3 ?= 12; 1*4+6 ?= 10 // ====TEST END==== //Note: The limitation happens between line 86 and line 88, we cannot insert any function here // whose stack is larger than 40 bytes.(Why is 40? check the inline assembler language)
结果在MacOSX和Ubuntu上(i386)都能通过简单的测试。但是可以看到,仅仅是简单的模拟,我们也得用到大量(按比例)的汇编,可读性很差,而且模拟程度非常有限,代码长度也更长。相反,对于这类一般功能的函数,Python可以很容易地模拟C语言的函数,而且模拟程度很高。
以上所述是小编给大家介绍的用C语言模仿Python函数的一种简单实现方法,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言。



