python调用C语言

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 

// 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 tu

你可能感兴趣的:(c/c++,python,json)