ctypes赋予了python类似于C语言一样的底层操作能力,通过ctypes模块可以调用动态链接库中的导出函数、构建复杂的c数据类型。
ctypes提供了三种不同的动态链接库加载方式:cdll(),windll(),oledll()。
HelloWorld.py:
import ctypes #导入ctypes模块 NULL = 0
m_string = "Hello World!!!"
m_title = "Ctype Dlg" user32 = ctypes.cdll.user32 #加载user32.dll
user32.MessageBoxW(NULL,m_string,m_title,NULL) #调用user32中的MessageBoxW函数
构建C语言数据类型:
ctypes基本数据类型映射表
参数类型预先设定好,或者在调用函数时再把参数转成相应的c_***类型。ctypes的类型对应如下:
ctypes type | C type | 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_bool | bool | bool |
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 longlong | 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 | float |
c_char_p | char * | string or None |
c_wchar_p | wchar_t * | unicode or None |
c_void_p | void * | int/long or None |
对应的指针类型是在后面加上"_p",如int*是c_int_p等等。在python中要实现c语言中的结构,需要用到类。
构建C结构体:
//c语言结构体 struct test
{
int num1;
int num2;
}; //python ctypes 结构体
from ctypes import *
class test(Structure):
_fields_ = [
("num1",c_int),
("num2",c_int),
]