标签:
ctypes赋予了python类似于C语言一样的底层操作能力,通过ctypes模块可以调用动态链接库中的导出函数、构建复杂的c数据类型。
ctypes提供了三种不同的动态链接库加载方式:cdll(),windll(),oledll()。
HelloWorld.py:
1 import ctypes #导入ctypes模块 2 3 NULL = 0 4 m_string = "Hello World!!!" 5 m_title = "Ctype Dlg" 6 7 user32 = ctypes.cdll.user32 #加载user32.dll 8 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结构体:
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 ]
标签:
原文地址:http://www.cnblogs.com/vawter/p/5901795.html