用C语言模仿Python函数

时间:2022-01-27 02:58:06

首先得说明一点,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))

Python Code

我们在C程序中适度地模拟其中的line_conf函数:

 /* MIT License

 Copyright (c) 2017 Yuandong-Chen

 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. */ /////////////////////////////////////////////////////////////////////////////// // 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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h> typedef int Func(); Func *line_conf(int x, int y,...)
{
va_list ap;
va_start(ap, y); asm volatile(
"push %%eax\n\t"
"subl $40, %%esp\n\t"
"movl 8(%%ebp), %%eax\n\t"
"movl %%eax, -36(%%ebp)\n\t"
"movl 12(%%ebp), %%eax\n\t"
"movl %%eax, -40(%%ebp)\n\t"
"addl $40, %%esp\n\t"
"pop %%eax\n\t"
:::"memory"
); if(va_arg(ap,int) == ){ LINE: asm volatile(
"push %%ebp\n\t"
"movl %%esp, %%ebp\n\t"
"movl 8(%%ebp), %%eax\n\t"
"imul -36(%%ebp), %%eax\n\t"
"addl -40(%%ebp), %%eax\n\t"
"movl %%ebp, %%esp\n\t"
"pop %%ebp\n\t"
"ret\n\t"
:::"memory","%eax"
);
}
__END:
va_end(ap);
return (Func *)(&&LINE);
} int main(int argc, const char *argv[]){
printf("====TEST START====\n");
printf("34*234+6 ?= %d\n",line_conf(,)());
printf("1*3+2 ?= %d; 324*65+3 ?= %d; 13*66+2 ?= %d\n",line_conf(,)(),line_conf(,)(),line_conf(,)()); int fd = line_conf(,)();
Func *fun = line_conf(,);
int a = ; // Limited point
printf("3*3+3 ?= %d; 1*4+6 ?= %d\n",fun(),fd);
printf("====TEST END====\n");
return ;
} // 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)

C Code

结果在MacOSX和Ubuntu上(i386)都能通过简单的测试。但是可以看到,仅仅是简单的模拟,我们也得用到大量(按比例)的汇编,可读性很差,而且模拟程度非常有限,代码长度也更长。

注意:这只是个玩具,别这么写代码,除非想搞破坏(充斥着各种漏洞,极易被侵入)。

用C语言模仿Python函数的更多相关文章

  1. 在使用python语言的open函数时,提示错误OSError&colon; &lbrack;Errno 22&rsqb; Invalid argument&colon; &OpenCurlyQuote;文件路径’

    如题,在使用python语言的open函数时,提示错误OSError: [Errno 22] Invalid argument: '文件路径',在查阅了大量资料后也得到了一些解决方案,但是这些解决方案 ...

  2. Python函数参数默认值的陷阱和原理深究&quot&semi;

    本文将介绍使用mutable对象作为Python函数参数默认值潜在的危害,以及其实现原理和设计目的 本博客已经迁移至: http://cenalulu.github.io/ 本篇博文已经迁移,阅读全文 ...

  3. C语言扩展Python模块

    1. 先创建一个PythonDemo.cpp文件: //c/c++中调用python脚本,配置步骤参见上一篇:C/C++与python交互 \  C/C++中调用python文件. #include ...

  4. Python开发【第三章】:Python函数介绍

    一. 函数介绍 1.函数是什么? 在学习函数之前,一直遵循面向过程编程,即根据业务逻辑从上到下实现功能,其往往用一长段代码来实现指定功能,开发过程中最常见的操作就是粘贴复制,也就是将之前实现的代码块复 ...

  5. Python函数解析

    对于Python的函数,我们需要记住的是: 1. 函数的默认返回值是None. 2. python是一个自上而下逐行解释并执行的语言.因此,函数的定义必须在函数被调用之前.同名的函数,后定义的会覆盖前 ...

  6. Python入门笔记&lpar;18&rpar;&colon;Python函数&lpar;1&rpar;&colon;基础部分

    一.什么是函数.方法.过程 推荐阅读:http://www.cnblogs.com/snandy/archive/2011/08/29/2153871.html 一般程序设计语言包含两种基本的抽象:过 ...

  7. python函数的返回值 讲解

    我们一起来聊聊python函数返回值的特殊情况,之前我也碰到过类似方面的问题,到后来查阅了一些资料后,发现原来是这样. 首先,写函数的时候,一定要写函数的文档,这样方便我们识别函数是做什么的.我记得很 ...

  8. windows 下 使用codeblocks 实现C语言对python的扩展

    本人比较懒就粘一下别人的配置方案了 从这开始到代码 摘自http://blog.csdn.net/yueguanghaidao/article/details/11538433 一直对Python扩展 ...

  9. python函数的参数传递问题---传值还是传引用?

    摘要:在python中,strings, tuples, 和numbers是不可更改的对象,而list,dict等则是可以修改的对象.不可更改对象的传递属于传值,可更改对象属于传引用.想要在函数中传递 ...

随机推荐

  1. 转换一个矩阵(2维数组)为HTML Table

    matrix[row][col],比如[ [ "Name", "Age" ], [ "Sam", 12 ] ] function (m) { ...

  2. IP子网划分

    CIDR值: 1.掩码255.0.0.0:/8(A类地址默认掩码) 2.掩码255.128.0.0:/9 3.掩码255.192.0.0:/10 4.掩码255.224.0.0:/11 5.掩码255 ...

  3. Asp&period;net MVC知识积累

    一.知识积累 http://yuangang.cnblogs.com/ 跟蓝狐学mvc教程专题目录:http://www.lanhusoft.com/Article/169.html 依赖注入:htt ...

  4. WebFormJS注册位置

    1. int height = Request.Browser.ScreenPixelsHeight; int width = Request.Browser.ScreenPixelsWidth; R ...

  5. 备忘&equals;&equals;&equals;&equals;&lbrack;HttpPost&rsqb;和&lbrack;AcceptVerbs&lpar;HttpVerbs&period;Post&rpar;&rsqb;区别

    1.共同点:[HttpPost]和[AcceptVerbs(HttpVerbs.Post)]都是只接受POST请求过来的数据. 2.不同点:在MVC中如果想一个action既可以回应POST请求也可以 ...

  6. java选择排序详解

    排序算法--选择排序 public class Selector implements ISortAble{ @Override public void sort(int[] a) { int n=a ...

  7. docker的相关使用

    1.docker ps 列出所有容器 2.docker images 查看docker镜像 3.docker run [OPTIONS] IMAGE [COMMAND] [ARG...] 运行容器 4 ...

  8. 学习linux的一些指令

    简单说一下我对linux的理解,linux只有一个根目录,所有目录都挂在该根目录上,磁盘进行分区,然后生成文件系统,挂到目录上,/etc/fstab用于记录系统配置,比如分区挂载点,开机自动挂载等等. ...

  9. Erlang cowboy websocket 服务器

    Erlang cowboy websocket 服务器 原文见于: http://marcelog.github.io/articles/erlang_websocket_server_cowboy_ ...

  10. win7搭建pyqt4开发环境

    版本 win7 64bit python2.7 https://www.python.org/ftp/python/2.7.13/python-2.7.13.amd64.msi pyqt4 https ...