收藏-Python调用windows下DLL详解

 

python中某些时候需要C做效率上的补充,在实际应用中,需要做部分数据的交互。使用python中的ctypes模块可以很方便的调用windowsdll(也包括linux下的so等文件),下面将详细的讲解这个模块(以windows平台为例子),当然我假设你们已经对windows下怎么写一个DLL是没有问题的。

引入ctypes库

from ctypes import *

假设你有了一个符合cdecl(这里强调调用约定是因为,stdcall调用约定和cdecl调用约定声明的导出函数,在用python加载使用的加载函数是不同的,后面会说明)调用约定的DLL(名字是add.dll),且有一个导出函数Add。

建立一个Python文件DllCall.py测试:

 

Python代码
  1. from ctypes import *  
  2.   
  3. dll = CDLL("add.dll")  
  4.   
  5. print dll.Add(1102)  

结果:103

上面是一个简单的例子。

1、加载DLL

上面已经说过,加载的时候要根据你将要调用的函数是符合什么调用约定的。

stdcall调用约定:两种加载方式

Python代码
  1. Objdll = ctypes.windll.LoadLibrary("dllpath")  
  2.   
  3. Objdll = ctypes.WinDLL("dllpath")  

cdecl调用约定:也有两种加载方式

Python代码
  1. Objdll = ctypes.cdll.LoadLibrary("dllpath")  
  2.   
  3. Objdll = ctypes.CDLL("dllpath")  

其实windll和cdll分别是WinDLL类和CDll类的对象。

2、调用dll中的方法

在1中加载dll的时候会返回一个DLL对象(假设名字叫Objdll),利用该对象就可以调用dll中的方法。

e.g.如果dll中有个方法名字叫Add(注意如果经过stdcall声明的方法,如果不是用def文件声明的导出函数的话,编译器会对函数名进行修改,这个要注意)

调用:nRet = Objdll.Add(12, 15) 即完成一次调用。

看起来调用似乎很简单,不要只看表象,呵呵,这是因为Add这个函数太简单了,现在假设函数需要你传入一个int类型的指针(int*),可以通过库中的byref关键字来实现,假设现在调用的函数的第三个参数是个int类型的指针。

Python代码
  1. intPara = c_int(9)  
  2.   
  3. dll.sub(23102, byref(intPara))  
  4.   
  5. print intPara.value  

如果是要传入一个char缓冲区指针,和缓冲区长度,方法至少有四种:

Python代码
  1. # char* – 1  
  2.   
  3. szPara = create_string_buffer(‘\0′*100)  
  4.   
  5. dll.PrintInfo(byref(szPara), 100);  
  6.   
  7. print szPara.value  
  8.   
  9. # char* – 2  
  10.   
  11. sBuf = ‘aaaaaaaaaabbbbbbbbbbbbbb’  
  12.   
  13. pStr = c_char_p( )  
  14.   
  15. pStr.value = sBuf  
  16.   
  17. #pVoid = ctypes.cast( pStr, ctypes.c_void_p ).value  
  18.   
  19. dll.PrintInfo(pStr, len(pStr.value))  
  20.   
  21. print pStr.value  
  22.   
  23. # char* – 3  
  24.   
  25. strMa = "\0"*20  
  26.   
  27. FunPrint  = dll.PrintInfo  
  28.   
  29. FunPrint.argtypes = [c_char_p, c_int]  
  30.   
  31. #FunPrint.restypes = c_void_p  
  32.   
  33. nRst = FunPrint(strMa, len(strMa))  
  34.   
  35. print strMa,len(strMa)  
  36.   
  37. # char* – 4  
  38.   
  39. pStr2 = c_char_p("\0")  
  40.   
  41. print pStr2.value  
  42.   
  43. #pVoid = ctypes.cast( pStr, ctypes.c_void_p ).value  
  44.   
  45. dll.PrintInfo(pStr2, len(pStr.value))  
  46.   
  47. print pStr2.value  

3、C基本类型和ctypes中实现的类型映射表

ctypes数据类型  C数据类型

c_char           char

c_short          short

c_int             int

c_long          long

c_ulong       unsign long

c_float         float

c_double     double

c_void_p     void

对应的指针类型是在后面加上"_p",如int*是c_int_p等等。

在python中要实现c语言中的结构,需要用到类。

4、DLL中的函数返回一个指针。

虽然这不是个好的编程方法,不过这种情况的处理方法也很简单,其实返回的都是地址,把他们转换相应的python类型,在通过value属性访问。

Python代码
  1. pchar = dll.getbuffer()  
  2.   
  3. szbuffer = c_char_p(pchar)  
  4.   
  5. print szbuffer.value  

5、处理C中的结构体类型

为什么把这个单独提出来说呢,因为这个是最麻烦也是最复杂的,在python里面申明一个类似c的结构体,要用到类,并且这个类必须继承自Structure。

先看一个简单的例子:

C里面dll的定义如下:

C++代码
  1. typedef struct _SimpleStruct  
  2.   
  3. {  
  4.   
  5.     int    nNo;  
  6.   
  7.     float  fVirus;   
  8.   
  9.     char   szBuffer[512];  
  10.   
  11. } SimpleStruct, *PSimpleStruct;  
  12.   
  13. typedef const SimpleStruct*  PCSimpleStruct;  
  14.   
  15. extern "C"int  __declspec(dllexport) PrintStruct(PSimpleStruct simp);  
  16.   
  17. int PrintStruct(PSimpleStruct simp)  
  18.   
  19. {   
  20.   
  21.     printf ("nMaxNum=%f, szContent=%s", simp->fVirus, simp->szBuffer);  
  22.   
  23. return simp->nNo;  
  24.   
  25. }  

Python的定义:

Python代码
  1. from ctypes import *  
  2.   
  3. class SimpStruct(Structure):  
  4.   
  5.     _fields_ = [ ("nNo", c_int),  
  6.   
  7.               ("fVirus", c_float),  
  8.   
  9.               ("szBuffer", c_char * 512)]  
  10.   
  11. dll = CDLL("AddDll.dll")  
  12.   
  13. simple = SimpStruct();  
  14.   
  15. simple.nNo = 16  
  16.   
  17. simple.fVirus = 3.1415926  
  18.   
  19. simple.szBuffer = "magicTong\0"  
  20.   
  21. print dll.PrintStruct(byref(simple))  

上面例子结构体很简单,如果结构体里面有指针,甚至是指向结构体的指针,python里面也有相应的处理方法。

下面这个例子来自网上,本来想自己写个,懒得写了,能说明问题就行:

C代码如下:

C++代码
  1. typedef struct   
  2.   
  3. {  
  4.   
  5. char words[10];  
  6.   
  7. }keywords;  
  8.   
  9. typedef struct   
  10.   
  11. {  
  12.   
  13. keywords *kws;  
  14.   
  15. unsigned int len;  
  16.   
  17. }outStruct;  
  18.   
  19. extern "C"int __declspec(dllexport) test(outStruct *o);  
  20.   
  21. int test(outStruct *o)  
  22.   
  23. {  
  24.   
  25. unsigned int i = 4;  
  26.   
  27. o->kws = (keywords *)malloc(sizeof(unsigned char) * 10 * i);  
  28.   
  29. strcpy(o->kws[0].words, "The First Data");  
  30.   
  31. strcpy(o->kws[1].words, "The Second Data");  
  32.   
  33. o->len = i;  
  34.   
  35. return 1;  
  36.   
  37. }  

Python代码如下:

Python代码
  1. class keywords(Structure):  
  2.   
  3.         _fields_ = [('words', c_char *10),]  
  4.   
  5. class outStruct(Structure):  
  6.   
  7.         _fields_ = [('kws', POINTER(keywords)),  
  8.   
  9.                     ('len', c_int),]  
  10.   
  11. o = outStruct()  
  12.   
  13. dll.test(byref(o))  
  14.   
  15. print o.kws[0].words;  
  16.   
  17. print o.kws[1].words;  
  18.   
  19. print o.len  

6、例子

说得天花乱坠,嘿嘿,还是看两个实际的例子。

例子一:

这 是一个GUID生成器,其实很多第三方的python库已经有封装好的库可以调用,不过这得装了那个库才行,如果想直接调用一些API,对于python 来说,也要借助一个第三方库才行,这个例子比较简单,就是用C++调用win32 API来产生GUID,然后python通过调用c++写的dll来获 得这个GUID

C++代码如下:

 

  1.  

    C++代码
    1. extern "C"__declspec(dllexportchar* newGUID();  
    2.   
    3. char* newGUID()  
    4.   
    5. {  
    6.   
    7. static char buf[64] = {0};  
    8.   
    9. statc GUID guid;  
    10.   
    11. if (S_OK == ::CoCreateGuid(&guid))  
    12.   
    13. {  
    14.   
    15. // "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X"  
    16.   
    17. _snprintf(buf, sizeof(buf),  
    18.   
    19. "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",  
    20.   
    21. guid.Data1,  
    22.   
    23. guid.Data2,  
    24.   
    25. guid.Data3,  
    26.   
    27. guid.Data4[0], guid.Data4[1],  
    28.   
    29. guid.Data4[2], guid.Data4[3],  
    30.   
    31. guid.Data4[4], guid.Data4[5],  
    32.   
    33. guid.Data4[6], guid.Data4[7]  
    34.   
    35. );  
    36.   
    37. ::MessageBox(NULL, buf, "GUID", MB_OK);  
    38.   
    39. }  
    40.   
    41. return (char*)buf;  
    42.   
    43. }  

Python代码如下:

    •  

      Python代码
        • def CreateGUID():  
        •    
        •     """ 
        •   
        •     创建一个全局唯一标识符 
        •   
        •     类似:E06093E2-699A-4BF2-A325-4F1EADB50E18 
        •   
        •     NewVersion 
        •   
        •     """  
        •    
        •     try:  
        •    
        •         # dll path  
        •    
        •         strDllPath = sys.path[0] + str(os.sep) + "createguid.dll"  
        •    
        •         dll = CDLL(strDllPath)  
        •    
        •         b = dll.newGUID()  
        •    
        •         a = c_char_p(b)                      
        •    
        •     except Exception, error:  
        •    
        •         print error  
        •    
        •         return ""   
        •    
        •     return a.value  
        •    
        •    

例子二:

这个例子是调用kernel32.dll中的createprocessA函数来启动一个记事本进程。


Python代码
  1. # -*- coding:utf-8 -*-  
  2.   
  3.   
  4. from ctypes import *  
  5.   
  6.   
  7. # 定义_PROCESS_INFORMATION结构体  
  8.   
  9. lass _PROCESS_INFORMATION(Structure):  
  10.   
  11. _fields_ = [('hProcess', c_void_p),  
  12.   
  13. ('hThread', c_void_p),  
  14.   
  15. ('dwProcessId', c_ulong),  
  16.   
  17. ('dwThreadId', c_ulong)]  
  18.   
  19.   
  20. # 定义_STARTUPINFO结构体  
  21.   
  22. class _STARTUPINFO(Structure):  
  23.   
  24. _fields_ = [('cb',c_ulong),  
  25.   
  26. ('lpReserved', c_char_p),  
  27.   
  28. ('lpDesktop', c_char_p),  
  29.   
  30. ('lpTitle', c_char_p),  
  31.   
  32. ('dwX', c_ulong),  
  33.   
  34. ('dwY', c_ulong),  
  35.   
  36. ('dwXSize', c_ulong),  
  37.   
  38. ('dwYSize', c_ulong),  
  39.   
  40. ('dwXCountChars', c_ulong),  
  41.   
  42. ('dwYCountChars', c_ulong),  
  43.   
  44. ('dwFillAttribute', c_ulong),  
  45.   
  46. ('dwFlags', c_ulong),  
  47.   
  48. ('wShowWindow', c_ushort),  
  49.   
  50. ('cbReserved2', c_ushort),  
  51.   
  52. ('lpReserved2', c_char_p),  
  53.   
  54. ('hStdInput', c_ulong),  
  55.   
  56. ('hStdOutput', c_ulong),  
  57.   
  58. ('hStdError', c_ulong)]  
  59.   
  60.   
  61.   
  62. NORMAL_PRIORITY_CLASS = 0×00000020 # 定义NORMAL_PRIORITY_CLASS  
  63.   
  64. kernel32 = windll.LoadLibrary("kernel32.dll"# 加载kernel32.dll  
  65.   
  66. CreateProcess = kernel32.CreateProcessA # 获得CreateProcess函数地址  
  67.   
  68. ReadProcessMemory = kernel32.ReadProcessMemory # 获得ReadProcessMemory函数地址  
  69.   
  70. WriteProcessMemory = kernel32.WriteProcessMemory # 获得WriteProcessMemory函数地址  
  71.   
  72. TerminateProcess = kernel32.TerminateProcess  
  73.   
  74.   
  75. # 声明结构体  
  76.   
  77. ProcessInfo = _PROCESS_INFORMATION()  
  78.   
  79. StartupInfo = _STARTUPINFO()  
  80.   
  81. fileName = ‘c:/windows/notepad.exe’ # 要进行修改的文件  
  82.   
  83. address = 0x0040103c # 要修改的内存地址  
  84.   
  85. strbuf = c_char_p("_"# 缓冲区地址  
  86.   
  87. bytesRead = c_ulong(0# 读入的字节数  
  88.   
  89. bufferSize = len(strbuf.value) # 缓冲区大小  
  90.   
  91.   
  92. # 创建进程  
  93.   
  94. CreateProcess(fileName, 0000, NORMAL_PRIORITY_CLASS,00, byref(StartupInfo), byref(ProcessIn  
  95. 文章转自:http://www.bonashen.com/archives/258
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值