一.c,ctypes和python的数据类型的对应关系
ctypes type ctype Python type 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_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 |
2.操作int
>>> fromctypesimport * >>> c=c_int(34) >>> c c_int(34) >>> c.value 34 >>> c.value=343 >>> c.value 343 |
3.操作字符串
>>> p=create_string_buffer(10) >>> p.raw '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' >>> p.value='fefefe' >>> p.raw 'fefefe\x00\x00\x00\x00' >>> p.value='fefeeeeeeeeeeeeeeeeeeeeeee' #字符串太长,报错 Traceback (mostrecentcalllast): File "<stdin>", line 1, in <module> ValueError: string toolong |
4.操作指针
>>> i=c_int(999) >>> pi=pointer(i) >>> pi <__main__.LP_c_intobject at 0x7f7be1983b00> >>> pi.value Traceback (mostrecentcalllast): File "<stdin>", line 1, in <module> AttributeError: 'LP_c_int' object hasnoattribute 'value' >>> pi.contents c_int(999) >>> pi.contents=c_long(34343) >>> pi.contents c_int(34343) |
通过pointer获取一个值的指针
通过contents获取一个指针的值
5.c的结构体
#定义一个c的structure,包含两个成员变量x和y >>> class POINT(Structure): ... _fields_=[('x',c_int),('y',c_int)] ... >>> point=POINT(2,4) >>> point <__main__.POINTobject at 0x7f7be1983b90> >>> point.x,point.y (2, 4) >>> porint=POINT(y=2) >>> porint <__main__.POINTobject at 0x7f7be1983cb0> >>> point=POINT(y=2) >>> point.x,point.y (0, 2) |
定义一个类型为POINT的数组
>>> POINT_ARRAY=POINT*3 >>> pa=POINT_ARRAY(POINT(2,3),POINT(2,4),POINT(2,5)) >>> for i in pa:print pa.y ... Traceback (mostrecentcalllast): File "<stdin>", line 1, in <module> AttributeError: 'POINT_Array_3' object hasnoattribute 'y' >>> for i in pa:print i.y ... 3 4 5 |
6.访问so文件
1.创建一个c文件
#include <stdio.h>
int hello_world(){
printf("Hello World\n");
return 0;
}
int main(){
hello_world();
return 0;
}
2.编译成动态链接库
gcchello_world.c -fPIC -shared -o hello_world.so
3.python中调用库中的函数
fromctypesimportcdll
c_lib=cdll.LoadLibrary('./hello_world.so')
c_lib.hello_world()
二.测试c的性能和python的差别
sum.c #include int sum(int num){ long sum=0; int i =0; for( i=1;i<=num;i++){ sum=sum+i; }; return sum; } int main(){ printf("%d",sum(10)); return 0; } |
测试方案:计算1-100的和
测试次数:100万次