Python Ctypes
优缺点:
- 优点:无需处理 Python 版本
- 缺点:不能多线程
步骤
- 写 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); } - 把
file.c文件编译为file.so:gcc file.c -shared -o file.so - 在Python中导入和使用
.sofrom 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 |
例子:
- C程序
#include<stdio.h> void MyTst(int x, float y) { printf("%d,%f\n", x, y); } - Python
import ctypes clib = ctypes.cdll.LoadLibrary("./file.so") # 整形无须转化,但浮点型必须转化 clib.MyTst(1, ctypes.c_float(2.000))