
ctypes是Python的一个外部库,可以使用python语言调用已经编译好的C语言函数以及数据类型并进行数据交换等。ctypes的官方文档在https://docs.python.org/3/library/ctypes.html
1、ctypes基本数据类型映射表

2、python调用c语言的函数库
(1)生成c语言函数
1 2 3 4 5 6 | #Step 1: test.c
# include <stdio.h>
int add(int a, int b)
{
return a + b;
}
|
(2)编译动态链接库生成 libtest.so文件(DLL)
1 | gcc -fPIC -shared test.c -o libtest.so
|
(3)调用DLL文件
1 2 3 4 5 6 7 | #Step 3: test.py
from ctypes import *
mylib = CDLL( "libtest.so" )或者cdll.LoadLibrary( "libtest.so" )
add = mylib.add
add.argtypes = [c_int, c_int] # 参数类型,两个int(c_int是ctypes类型,见上表)
add.restype = c_int # 返回值类型,int (c_int 是ctypes类型,见上表)
sum = add(3, 6)
|
3、指针和引用
对指针实例赋值只会改变其指向的内存地址,而不是改变内存的内容。指针实例有一个contents属性,返回这个指针所指向的对象。

1 2 3 4 5 6 | from ctype import *
i = c_int(1)
pi = POINTER(c_int)(i)
pi2 = pointer(i)
print pi.contents #返回指针指向对象的值
print pi2.contents
|
pointer 和 POINTER 的区别是,pointer 返回一个实例,POINTER 返回一个类型。
4、结构类型数据
Structures和Unions必须继承Structure和Union基础类,它们都在ctypes模块中定义,每一个子类必须定义个fields属性,fields是一个二维的tuples列表,包含着每个field的name及type,这field类型必须是一个ctypes类型,如c_int,或者任何其他的继承ctypes的类型,如Structure、Union、Array、指针等。
1 2 3 4 5 | from ctypes import *
import types
class Test(Structure):
_fields_ = [( 'x' , c_int),( 'y' , c_char)]
test1 = Test(1, 2)
|
如结构体用于链表操作,即包含指向结构体指针时,则需如下定义:
1 2 3 4 5 | from ctypes import *
import types
class Test(Structure):
pass
Test._fields_ = [( 'x' , c_int),( 'y' , c_char),( 'next' , POINTER(Test))]
|
python学习网,大量的免费python视频教程,欢迎在线学习!