python调用C语言

本文介绍了Python在GIL限制下如何通过c extension、Cython和ctypes调用C语言实现多线程。详细讲解了每个方法的原理、示例及编译过程,并进行了性能基准测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python由于在实现多线程的情况下,由于GIL(全局解释器锁)的存在,只能实现伪线程,要想真正实现多线程,可以调用第三方的扩展,使用C语言编写一些需要实现多线程的业务逻辑。

最常用的调用C函数的方式,分别是c extension,Cython和ctypes。

c extension

介绍

python标准库包含了很多使用C开发的扩展模块,比如对性能要求很高的json库。开发者同样可以使用C开发扩展,这是最原始也是最底层的扩展python的方式。

示例

demomodule.c

python的扩展模块由以下几部分组成:

  • Python.h
  • C函数
  • 接口函数(python代码调用的函数)到C函数的映射表
  • 初始化函数
 
// pulls in the Python API 
#include <Python.h>

// C function always has two arguments, conventionally named self and args
// The args argument will be a pointer to a Python tuple object containing the arguments.
// Each item of the tuple corresponds to an argument in the call’s argument list.
static PyObject *
demo_add(PyObject *self, PyObject *args)
{
    const int a, b;
    // convert PyObject to C values
    if (!PyArg_ParseTuple(args, "ii", &a, &b))
        return NULL;
    return Py_BuildValue("i", a+b);
}

// module's method table
static PyMethodDef DemoMethods[] = {
    {"add", demo_add, METH_VARARGS, "Add two integers"},
    {NULL, NULL, 0, NULL} 
};

// module’s initialization function
PyMODINIT_FUNC
initdemo(void)
{
    (void)Py_InitModule("demo", DemoMethods);
}
setup.py

编译扩展模块通常使用distutils或setuptools,它会自动调用gcc完成编译和链接。

from distutils.core import setup, Extension

module1 = Extension('demo',
                    sources = ['demomodule.c']
                    )

setup (name = 'a demo extension module',
       version = '1.0',
       description = 'This is a demo package',
       ext_modules = [module1])

  执行

python setup.py build_ext --inplace

  会在当前目录生

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值