首页 > 代码库 > ctypes 模块

ctypes 模块

  ctypes赋予了python类似于C语言一样的底层操作能力,通过ctypes模块可以调用动态链接库中的导出函数、构建复杂的c数据类型。

  ctypes提供了三种不同的动态链接库加载方式:cdll(),windll(),oledll()。

 

  HelloWorld.py:

1 import ctypes   #导入ctypes模块    2 3 NULL = 04 m_string = "Hello World!!!"5 m_title = "Ctype Dlg"6 7 user32 = ctypes.cdll.user32    #加载user32.dll8 user32.MessageBoxW(NULL,m_string,m_title,NULL)    #调用user32中的MessageBoxW函数

 

 

 

构建C语言数据类型:

 ctypes基本数据类型映射表

参数类型预先设定好,或者在调用函数时再把参数转成相应的c_***类型。ctypes的类型对应如下:

ctypes typeC typePython Type
c_charchar1-character string
c_wcharwchar_t1-character unicode string
c_bytecharint/long
c_ubyteunsigned charint/long
c_boolboolbool
c_shortshortint/long
c_ushortunsigned shortint/long
c_intintint/long
c_uintunsigned intint/long
c_longlongint/long
c_ulongunsigned longint/long
c_longlong__int64 or longlongint/long
c_ulonglongunsigned __int64 or unsigned long longint/long
c_floatfloatfloat
c_doubledoublefloat
c_longdoublelong double floatfloat
c_char_pchar *string or None
c_wchar_pwchar_t *unicode or None
c_void_pvoid *int/long or None
   

对应的指针类型是在后面加上"_p",如int*是c_int_p等等。在python中要实现c语言中的结构,需要用到类。 

 

构建C结构体:

  

 1 //c语言结构体 2  3 struct test 4 { 5     int num1; 6     int num2;        7 }; 8  9 //python ctypes 结构体10 from ctypes import *11 class test(Structure):12 _fields_ = [13 ("num1",c_int),14 ("num2",c_int),15 ]

 

ctypes 模块