参考资料

ctypes简介

一直对不同语言间的交互感兴趣,python和C语言又深有渊源,所以对python和c语言交互产生了兴趣。

最近了解了python提供的一个外部函数库 ctypes, 它提供了C语言兼容的几种数据类型,并且可以允许调用C编译好的库。

这里是阅读相关资料的一个记录,内容大部分来自官方文档

数据类型

ctypes 提供了一些原始的C语言兼容的数据类型,参见下表,其中第一列是在ctypes库中定义的变量类型,第二列是C语言定义的变量类型,第三列是Python语言在不使用ctypes时定义的变量类型。

| ctypes type  | C type                                 | Python type                |
|--------------+----------------------------------------+----------------------------|
| c_bool | _Bool | bool (1) |
| c_char | char | 1-character string |
| c_wchar | wchar_t | 1-character unicode string |
| c_byte | char | int/long |
| c_ubyte | unsigned char | int/long |
| c_short | short | int/long |
| c_ushort | unsigned short | int/long |
| c_int | int | int/long |
| c_uint | unsigned int | int/long |
| c_long | long | int/long |
| c_ulong | unsigned long | int/long |
| c_longlong | __int64 or long long | int/long |
| c_ulonglong | unsigned __int64 or unsigned long long | int/long |
| c_float | float | float |
| c_double | double | float |
| c_longdouble | long double | float |
| c_char_p | char * (NUL terminated) | string or None |
| c_wchar_p | wchar_t * (NUL terminated) | unicode or None |
| c_void_p | void * | int/long or None |

创建简单的ctypes类型如下:

>>> c_int()
c_long(0)
>>> c_char_p("Hello, World")
c_char_p('Hello, World')
>>> c_ushort(-3)
c_ushort(65533)
>>>

使用 .value 访问和改变值:

>>> i = c_int(42)
>>> print i
c_long(42)
>>> print i.value
42
>>> i.value = -99
>>> print i.value
-99
>>>

改变指针类型的变量值:

>>> s = "Hello, World"
>>> c_s = c_char_p(s)
>>> print c_s
c_char_p('Hello, World')
>>> c_s.value = "Hi, there"
>>> print c_s
c_char_p('Hi, there')
>>> print s # 一开始赋值的字符串并不会改变, 因为这里指针的实例改变的是指向的内存地址,不是直接改变内存里的内容
Hello, World
>>>

如果需要直接操作内存地址的数据类型:

>>> from ctypes import *
>>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
>>> print sizeof(p), repr(p.raw)
3 '\x00\x00\x00'
>>> p = create_string_buffer("Hello") # create a buffer containing a NUL terminated string
>>> print sizeof(p), repr(p.raw) # .raw 访问内存里存储的内容
6 'Hello\x00'
>>> print repr(p.value) # .value 访问值
'Hello'
>>> p = create_string_buffer("Hello", 10) # create a 10 byte buffer
>>> print sizeof(p), repr(p.raw)
10 'Hello\x00\x00\x00\x00\x00'
>>> p.value = "Hi"
>>> print sizeof(p), repr(p.raw)
10 'Hi\x00lo\x00\x00\x00\x00\x00'
>>>

下面的例子演示了使用C的数组和结构体:

>>> class POINT(Structure):                 # 定义一个结构,内含两个成员变量 x,y,均为 int 型
... _fields_ = [("x", c_int),
... ("y", c_int)]
...
>>> point = POINT(2,5) # 定义一个 POINT 类型的变量,初始值为 x=2, y=5
>>> print point.x, point.y # 打印变量
2 5
>>> point = POINT(y=5) # 重新定义一个 POINT 类型变量,x 取默认值
>>> print point.x, point.y # 打印变量
0 5
>>> POINT_ARRAY = POINT * 3 # 定义 POINT_ARRAY 为 POINT 的数组类型
# 定义一个 POINT 数组,内含三个 POINT 变量
>>> pa = POINT_ARRAY(POINT(7, 7), POINT(8, 8), POINT(9, 9))
>>> for p in pa: print p.x, p.y # 打印 POINT 数组中每个成员的值
...
7 7
8 8
9 9

创建指针实例

>>> from ctypes import *
>>> i = c_int(42)
>>> pi = pointer(i)
>>> >>> pi.contents
c_long(42)
>>>

使用cast()类型转换

>>> class Bar(Structure):
... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
...
>>> bar = Bar()
>>> bar.values = (c_int * 3)(1, 2, 3)
>>> bar.count = 3
>>> for i in range(bar.count):
... print bar.values[i]
...
1
2
3
>>> >>> bar = Bar()
>>> bar.values = cast((c_byte * 4)(), POINTER(c_int)) # 这里转成需要的类型
>>> print bar.values[0]
0
>>>

类似于C语言定义函数时,会先定义返回类型,然后具体实现再定义,当遇到下面这种情况时,也需要这么干:

>>> class cell(Structure):
... _fields_ = [("name", c_char_p),
... ("next", POINTER(cell))]
...
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in cell
NameError: name 'cell' is not defined
>>> # 不能调用自己,所以得像下面这样
>>> from ctypes import *
>>> class cell(Structure):
... pass
...
>>> cell._fields_ = [("name", c_char_p),
... ("next", POINTER(cell))]
>>>

调用.so/.dll

可以简单地将"so"和"dll"理解成Linux和windows上动态链接库的指代,这里我们以Linux为例。注意,ctypes提供的接口会在不同系统上有出入,比如为了加载动态链接库, 在Linux上提供的是 cdll, 而在Windows上提供的是 windlloledll

加载动态链接库

from ctypes import *
>>> cdll.LoadLibrary("libc.so.6")
<CDLL 'libc.so.6', handle ... at ...>
>>> libc = CDLL("libc.so.6")
>>> libc
<CDLL 'libc.so.6', handle ... at ...>
>>>

调用加载的函数

>>> print libc.time(None)
1150640792
>>> print hex(windll.kernel32.GetModuleHandleA(None))
0x1d000000
>>>

设置个性化参数

ctypes会寻找 _as_paramter_ 属性来用作调用函数的参数传入,这样就可以传入自己定义的类作为参数,示例如下:

>>> class Bottles(object):
... def __init__(self, number):
... self._as_parameter_ = number
...
>>> bottles = Bottles(42)
>>> printf("%d bottles of beer\n", bottles)
42 bottles of beer
19
>>>

指定函数需要参数类型和返回类型

argtypesrestype 来指定调用的函数返回类型。

>>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
>>> printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2)
String 'Hi', Int 10, Double 2.200000
37
>>> >>> strchr = libc.strchr
>>> strchr("abcdef", ord("d"))
8059983
>>> strchr.restype = c_char_p # c_char_p is a pointer to a string
>>> strchr("abcdef", ord("d"))
'def'
>>> print strchr("abcdef", ord("x"))
None
>>>

这里我只是列出了 ctypes 最基础的部分,还有很多细节请参考官方文档。

题外话

这两天文章没有写,先是早出晚归出去玩了一整天,然后加班到凌晨3点左右,一天一篇计划划水得严重啊…

Python 外部函数调用库ctypes简介的更多相关文章

  1. Python数据分析Pandas库方法简介

    Pandas 入门 Pandas简介 背景:pandas是一个Python包,提供快速,灵活和富有表现力的数据结构,旨在使“关系”或“标记”数据的使用既简单又直观.它旨在成为在Python中进行实际, ...

  2. Python数据分析Numpy库方法简介(一)

    Numpy功能简介: 1.官网:www.numpy.org 2.特点:(1)高效的多维矩阵/数组; (2);复杂的广播功能 (3):有大量的内置数学统计函数 矩阵(多维数组): 一维数组:  ([ 值 ...

  3. Python数据分析Numpy库方法简介(四)

    Numpy的相关概念2 副本和视图 副本:复制 三种情况属于浅copy 赋值运算 切片 视图:链接,操作数组是,返回的不是副本就是视图 c =a.view().创建a的视图/影子和切片一样都是浅cop ...

  4. Python数据分析Numpy库方法简介(三)

    补充: np.ceil()向上取整 3.1向上取整是4 np.floor()向下取整 数组名.resize((m,n)) 重置行列 基础操作 np.random.randn()符合正态分布(钟行/高斯 ...

  5. Python数据分析Numpy库方法简介(二)

    数据分析图片保存:vg 1.保存图片:plt.savefig(path) 2.图片格式:jpg,png,svg(建议使用,不失真) 3.数据存储格式: excle,csv csv介绍 csv就是用逗号 ...

  6. 大量Python开源第三方库资源分类整理,含菜鸟教程章节级别链接

    Python是一种面向对象的解释型计算机程序设计语言,由荷兰人Guido van Rossum于1989年发明.因其具有丰富和强大的库,它常被称为胶水语言,能够把用其它语言制作的各种模块(尤其是C/C ...

  7. python PIL 图像处理库简介(一)

    1. Introduction     PIL(Python Image Library)是python的第三方图像处理库,但是由于其强大的功能与众多的使用人数,几乎已经被认为是python官方图像处 ...

  8. python 各种开源库

    测试开发 来源:https://www.jianshu.com/p/ea6f7fb69501 Web UI测试自动化 splinter - web UI测试工具,基于selnium封装. 链接 sel ...

  9. Python常用的库简单介绍一下

    Python常用的库简单介绍一下fuzzywuzzy ,字符串模糊匹配. esmre ,正则表达式的加速器. colorama 主要用来给文本添加各种颜色,并且非常简单易用. Prettytable ...

随机推荐

  1. NoSQL(Not Only SQL)

    Everything has its properties and has relation with each other. All in world can be related to each ...

  2. python 修改xml文件

    在百度知道里面有人问了这么一个问题: 有一个xml文件:<root>text <a/> <a/> ...这里省略n个<a/> <root>想 ...

  3. Linux远程桌面(二)

    上一篇远程桌面采用的独立服务配置不适用于过多用户,这一篇采用超级Internet服务器搭建vnc服务可以解决多用户问题.  vnc之xinetd服务搭建配置 Linux远程桌面(一):vnc之独立服务 ...

  4. PHP : url中出现乱码问题

    例子: 在html中,将数据传到url中 当我点击“提交回复”后,跳转页面中将显示: 我们获取这个参数: 但是由于传过来的参数是中文,url会进行自动的解析成二进制的代码,那我们后台接受到的数据是解析 ...

  5. PointCNN 论文翻译解析

    1. 前言 卷积神经网络在二维图像的应用已经较为成熟了,但 CNN 在三维空间上,尤其是点云这种无序集的应用现在研究得尤其少.山东大学近日公布的一项研究提出的 PointCNN 可以让 CNN 在点云 ...

  6. selenium项目--读取测试用例

    读取测试用例 一直我们都没有考虑过读取测试用例的事,我们现在这样设计测试用例有两个好的点,在执行方法时,打印测试用例,方便知道执行的内容是什么,在报告展示时,把测试用例的结果展示出来 实现方案:目前我 ...

  7. phpmyadmin 打开数据表较多,数据量较大的数据库时出现超时的解决办法

    用phpmyadmin打开数据表较多,数据量较大的数据库时,会出现超时,或者等半天打开了说数据库没有表.并且即便打开了,再进行其他浏览,编辑,sql等操作,页面也是相当慢的,慢等几乎无法忍受.这里慢也 ...

  8. 2017.10.18 微机原理与接口----汇编语言语法和DOS功能调用

    4.1 汇编语言中的基本数据 ·标识符 ·常数 ·变量具有三个属性: (1)段地址(SEG):变量所在段的段地址 (2)偏移地址(OFFSET):变量所在段内的偏移地址 (3)类型(TYPE):每个变 ...

  9. c#中的 MessageBox 弹出提示框的用法

    MessageBox.Show(<字符串str> Text, <字符串str> Title, <整型int> nType,MessageBoxIcon); 例:Me ...

  10. CCF CSP 201712-2 游戏

    题目链接:http://118.190.20.162/view.page?gpid=T67 问题描述 有n个小朋友围成一圈玩游戏,小朋友从1至n编号,2号小朋友坐在1号小朋友的顺时针方向,3号小朋友坐 ...