【Python-c】Python 与 C 混合编程

2021年11月06日    Author:Guofei

文章归类: 0x11_算法平台    文章编号: 173


版权声明:本文作者是郭飞。转载随意,但需要标明原文链接,并通知本人
原文链接:https://www.guofei.site/2021/11/06/python_c.html

Edit

Python Ctypes

优缺点:

  • 优点:无需处理 Python 版本
  • 缺点:不能多线程

步骤

  1. 写 c 文件, 保存为 file.c
    #include<stdio.h>
    void add()
    {
    int sum=0;
    for(int i=0;i<1000;i++)
    sum+=i;
    printf("sum:%d\n",sum);
    }
    
  2. file.c 文件编译为 file.sogcc file.c -shared -o file.so
  3. 在Python中导入和使用 .so
    from ctypes import *
    clib = cdll.LoadLibrary("./file.so")
    clib.add()
    

如何同时支持 windows/Linux : https://www.bilibili.com/video/BV17y4y1W7BY?p=3

数据类型

ctypes 类型 C 类型 Python 数据类型
c_bool _Bool bool (1)
c_char char 单字符字节串对象
c_wchar wchar_t 单字符字符串
c_byte char int
c_ubyte unsigned char int
c_short short int
c_ushort unsigned short int
c_int int int
c_uint unsigned int int
c_long long int
c_ulong unsigned long int
c_longlong __int64 或 long long int
c_ulonglong unsigned __int64 或 unsigned long long int
c_size_t size_t int
c_ssize_t ssize_t 或 Py_ssize_t int
c_float float float
c_double double float
c_longdouble long double float
c_char_p char * (NUL terminated) 字节串对象或 None
c_wchar_p wchar_t * (NUL terminated) 字符串或 None
c_void_p void * int 或 None

例子:

  1. C程序
    #include<stdio.h>
    void MyTst(int x, float y)
    {
      printf("%d,%f\n", x, y);
    }
    
  2. Python
    import ctypes
    clib = ctypes.cdll.LoadLibrary("./file.so")
    # 整形无须转化,但浮点型必须转化
    clib.MyTst(1, ctypes.c_float(2.000))
    

您的支持将鼓励我继续创作!
WeChatQR AliPayQR qr_wechat