官方文档:

https://docs.python.org/3/extending/index.html

  • 交叉编译到aarch64上面

以交叉编译到aarch64上面为例,下面是Extest.c的实现:

  1. #include <Python.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. #define BUFSIZE 10
  7.  
  8. int fac(int n) {
  9. if (n < )
  10. return ;
  11. return n * fac(n - );
  12. }
  13.  
  14. static PyObject * Extest_fac(PyObject *self, PyObject *args) {
  15. int res;//计算结果值
  16. int num;//参数
  17. PyObject* retval;//返回值
  18.  
  19. //i表示需要传递进来的参数类型为整型,如果是,就赋值给num,如果不是,返回NULL;
  20. res = PyArg_ParseTuple(args, "i", &num);
  21. if (!res) {
  22. //包装函数返回NULL,就会在Python调用中产生一个TypeError的异常
  23. return NULL;
  24. }
  25. res = fac(num);
  26. //需要把c中计算的结果转成python对象,i代表整数对象类型。
  27. retval = (PyObject *)Py_BuildValue("i", res);
  28. return retval;
  29. }
  30.  
  31. char *reverse(char *s) {
  32. register char t;
  33. char *p = s;
  34. char *q = (s + (strlen(s) - ));
  35. while (p < q) {
  36. t = *p;
  37. *p++ = *q;
  38. *q-- = t;
  39. }
  40. return s;
  41. }
  42.  
  43. static PyObject *
  44. Extest_reverse(PyObject *self, PyObject *args) {
  45. char *orignal;
  46. if (!(PyArg_ParseTuple(args, "s", &orignal))) {
  47. return NULL;
  48. }
  49. return (PyObject *)Py_BuildValue("s", reverse(orignal));
  50. }
  51.  
  52. static PyObject *
  53. Extest_doppel(PyObject *self, PyObject *args) {
  54. char *orignal;
  55. char *reversed;
  56. PyObject * retval;
  57. if (!(PyArg_ParseTuple(args, "s", &orignal))) {
  58. return NULL;
  59. }
  60. retval = (PyObject *)Py_BuildValue("ss", orignal, reversed=reverse(strdup(orignal)));
  61. free(reversed);
  62. return retval;
  63. }
  64.  
  65. static PyMethodDef
  66. ExtestMethods[] = {
  67. {"fac", Extest_fac, METH_VARARGS},
  68. {"doppel", Extest_doppel, METH_VARARGS},
  69. {"reverse", Extest_reverse, METH_VARARGS},
  70. {NULL, NULL},
  71. };
  72.  
  73. static struct PyModuleDef ExtestModule = {
  74. PyModuleDef_HEAD_INIT,
  75. "Extest",
  76. NULL,
  77. -,
  78. ExtestMethods
  79. };
  80.  
  81. PyMODINIT_FUNC PyInit_Extest(void)
  82. {
  83. return PyModule_Create(&ExtestModule);
  84. }

采用手动编译, Makefile如下:

  1. CFLAGS = -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
  2. CFLAGS += -fPIC -I /home/pengdonglin/src/qemu/python_cross_compile/Python3/aarch64/include/python3.6m
  3. CC = /home/pengdonglin/src/qemu/aarch64/gcc-linaro-aarch64-linux-gnu-4.9-.07_linux/bin/aarch64-linux-gnu-gcc
  4.  
  5. all:Extest.so
  6.  
  7. Extest.o: Extest.c
  8. $(CC) $(CFLAGS) -c $^ -o $@
  9.  
  10. Extest.so: Extest.o
  11. $(CC) -pthread -shared $^ -o $@
  12. cp $@ /home/pengdonglin/src/qemu/python_cross_compile/Python3/aarch64/lib/python3./site-packages/
  13.  
  14. clean:
  15. $(RM) *.o *.so
  16.  
  17. .PHONY: clean all

执行make命令,就会在当前目录下生成一个Extest.so文件,然后将其放到板子上面的/usr/lib/python3.6/site-packages/下面即可

测试:

  1. [root@aarch64 root]# cp /mnt/Extest.so /usr/lib/python3./site-packages/
  2. [root@aarch64 root]# python3
  3. Python 3.6. (default, Mar , ::)
  4. [GCC 4.9. (prerelease)] on linux
  5. Type "help", "copyright", "credits" or "license" for more information.
  6. >>> import Extest
  7. >>> Extest.fac()
  8.  
  9. >>> Extest.reverse("pengdonglin")
  10. 'nilgnodgnep'
  11. >>> Extest.doppel("pengdonglin")
  12. ('pengdonglin', 'nilgnodgnep')
  • 编译到x86_64上面

编写setup.py如下:

  1. #/usr/bin/env python3
  2.  
  3. from distutils.core import setup, Extension
  4.  
  5. MOD = 'Extest'
  6. setup(name=MOD, ext_modules=[Extension(MOD, sources=['Extest.c'])])

编译

  1. $/usr/local/bin/python3 ./setup.py build
  2. running build
  3. running build_ext
  4. building 'Extest' extension
  5. creating build
  6. creating build/temp.linux-x86_64-3.6
  7. gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/python3.6m -c Extest.c -o build/temp.linux-x86_64-3.6/Extest.o
  8. creating build/lib.linux-x86_64-3.6
  9. gcc -pthread -shared build/temp.linux-x86_64-3.6/Extest.o -o build/lib.linux-x86_64-3.6/Extest.cpython-36m-x86_64-linux-gnu.so

可以看到,在Python3上面用setup.py默认生成的so的名字是Extest.cpython-36m-x86_64-linux-gnu.so

安装

  1. $sudo /usr/local/bin/python3 ./setup.py install
  2. [sudo] password for pengdonglin:
  3. running install
  4. running build
  5. running build_ext
  6. running install_lib
  7. copying build/lib.linux-x86_64-3.6/Extest.cpython-36m-x86_64-linux-gnu.so -> /usr/local/lib/python3./site-packages
  8. running install_egg_info
  9. Writing /usr/local/lib/python3./site-packages/Extest-0.0.-py3..egg-info

可以看到,将Extest.cpython-36m-x86_64-linux-gnu.so拷贝到了/usr/local/lib/python3.6/site-packages下面。

测试

在PC上面输入python3命令:

  1. $python3
  2. Python 3.6. (default, Mar , ::)
  3. [GCC 4.8.] on linux
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. >>> import Extest
  6. >>> Extest
  7. <module 'Extest' from '/usr/local/lib/python3.6/site-packages/Extest.cpython-36m-x86_64-linux-gnu.so'>
  8. >>> Extest.fac()
  9.  
  10. >>> Extest.reverse("pengdonglin")
  11. 'nilgnodgnep'
  12. >>> Extest.doppel("pengdonglin")
  13. ('pengdonglin', 'nilgnodgnep')
  14. >>>

可以在第7行看到加载的Extest.so的路径,而且我们只需要import Extest就可以了。

完。

用C扩展Python3的更多相关文章

  1. 使用C语言扩展Python3

    使用C语言扩展Python3.在Python3中正确调用C函数. 1. 文件demo.c #include <Python.h> // c function static PyObject ...

  2. python3.5之mysql扩展

    最近在学习廖雪峰的python3的教程,这是官方http://www.liaoxuefeng.com/,建议大家想学习python的同学可以去看看,真的是在网上能找到的最好文本教程,没有之一 在廖老实 ...

  3. 在python3中安装mysql扩展,No module named 'ConfigParser'

    在python2.7中,我们安装的是 MySqldb或这 MySQL-python,能够正却安装,但在python3中,由于 其使用的扩展  ConfigParser 已经改名为 configpars ...

  4. Python3 与 C# 扩展之~模块专栏

      代码裤子:https://github.com/lotapp/BaseCode/tree/maste 在线编程:https://mybinder.org/v2/gh/lotapp/BaseCode ...

  5. Python3 与 C# 扩展之~基础衍生

      本文适应人群:C# or Python3 基础巩固 代码裤子: https://github.com/lotapp/BaseCode 在线编程: https://mybinder.org/v2/g ...

  6. Python3 与 C# 扩展之~基础拓展

      上次知识回顾:https://www.cnblogs.com/dotnetcrazy/p/9278573.html 代码裤子:https://github.com/lotapp/BaseCode ...

  7. python3.4学习笔记(三) idle 清屏扩展插件

    python3.4学习笔记(三) idle 清屏扩展插件python idle 清屏问题的解决,使用python idle都会遇到一个常见而又懊恼的问题——要怎么清屏?在stackoverflow看到 ...

  8. Python3.x:python: extend (扩展) 与 append (追加) 的区别

    Python3.x:python: extend (扩展) 与 append (追加) 的区别 1,区别: append() 方法向列表的尾部添加一个新的元素.只接受一个参数: extend()方法只 ...

  9. python3.x 匿名函数lambda_扩展sort

    #匿名函数lambda 参数: 表达式关键字 lambda 说明它是一个匿名函数,冒号 : 前面的变量是该匿名函数的参数,冒号后面是函数的返回值,注意这里不需使用 return 关键字. ambda只 ...

随机推荐

  1. 支付宝:电脑网站沙箱测试(Java)

    1.下载电脑网站的官方demo: 下载地址:https://docs.open.alipay.com/270/106291/ 2.下载解压导入eclipse readme.txt请好好看一下. 只有一 ...

  2. sass和scss相关知识

    参考地址:http://www.imooc.com/learn/311 什么是css预处理器? CSS 预处理器定义了一种新的语言,其基本思想是,用一种专门的编程语言,为 CSS 增加了一些编程的特性 ...

  3. 【招聘】这一次,我们Hold住了世界杯

    作为国内最大的云计算服务商,阿里云在视频领域拥有绝对的技术优势,全球范围内拥有1500多个CDN节点,带宽储备120多T,不仅为优酷.CNTV.CCTV5提供技术支撑,还承担了全网70%的世界杯流量. ...

  4. C#获取特定进程CPU和内存使用率

    首先是获取特定进程对象,可以使用Process.GetProcesses()方法来获取系统中运行的所有进程,或者使用Process.GetCurrentProcess()方法来获取当前程序所对应的进程 ...

  5. Java编程的逻辑 (24) - 异常 (上)

    ​本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http: ...

  6. read命令

    read命令从键盘读取变量的值,通常用在shell脚本中与用户进行交互的场合. 该命令可以一次读取多个变量的值,变量和输入的值都需要使用空格隔开.在read命令后面,如果没有指定变量名,读取的数据将被 ...

  7. 【LOJ】#2084. 「NOI2016」网格

    题解 之前用的mapTLE了,今天用了个hash把题卡了过去,AC数++ 我们只要保留一个点为中心周围5 * 5个格子就可以 如果一个点周围5*5个格子有两个不连通,那么显然输出0 如果一个出现了一个 ...

  8. 1195: [HNOI2006]最短母串

    思路:好像以前谁问过我这题...  状个压就好啦, 把包含在其他串中的字符串删掉, 预处理除每两个字符串之间的关系, dp[ state ][ i ] 表示在state的状态下, 最后一个字符串是第i ...

  9. myBatsi调用存储过程

    1.结构 2.准备数据 建表和插入数据 CREATE TABLE p_user( id INT PRIMARY KEY AUTO_INCREMENT, name ), sex ) ); INSERT ...

  10. hibernate Validator 6.X 的学习,bean的约束(主要包括的是容器元素的验证)

    1. 四:案例二(property的验证) 1.