如何使用Python調用windows下DLL中方法

在python中某些時候需要C做效率上的補充,在實際應用中,需要做部分數據的交互。使用python中的ctypes模塊可以很方便的調用windows的dll(也包括linux下的so等文件),下面將詳細的講解這個模塊(以windows平臺為例子),當然我假設你們已經對windows下怎麼寫一個DLL是沒有問題的。

引入ctypes庫

from ctypes import * 
1

假設你已經有了一個的DLL(名字是add.dll),且該DLL有一個符合cdecl(這裡強調調用約定是因為,stdcall調用約定和cdecl調用約定聲明的導出函數,在使用python加載時使用的加載函數是不同的,後面會有說明)調用約定的導出函數Add。

建立一個Python文件DllCall.py測試:

from ctypes import * 
dll = CDLL("add.dll")
print dll.Add(1, 102)
1
2
3

結果:103

上面是一個簡單的例子。下面簡單聊一下調用流程:

1、加載DLL

上面已經說過,加載的時候要根據你將要調用的函數是符合什麼調用約定的。

stdcall調用約定:兩種加載方式

Objdll = ctypes.windll.LoadLibrary("dllpath") 
Objdll = ctypes.WinDLL("dllpath")

1
2

cdecl調用約定:也有兩種加載方式

Objdll = ctypes.cdll.LoadLibrary("dllpath") 
Objdll = ctypes.CDLL("dllpath")
其實windll和cdll分別是WinDLL類和CDll類的對象。
1
2
3

2、調用dll中的方法

在1中加載dll的時候會返回一個DLL對象(假設名字叫Objdll),利用該對象就可以調用dll中的方法。

e.g.如果dll中有個方法名字叫Add(注意如果經過stdcall聲明的方法,如果不是用def文件聲明的導出函數或者extern “C” 聲明的話,編譯器會對函數名進行修改,這個要注意,我想你們懂的。)

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

看起來調用似乎很簡單,不要只看表象,呵呵,這是因為Add這個函數太簡單了,現在假設函數需要你傳入一個int類型的指針(int*),可以通過庫中的byref關鍵字來實現,假設現在調用的函數的第三個參數是個int類型的指針。

intPara = c_int(9) 
dll.sub(23, 102, byref(intPara))
print intPara.value
1
2
3

如果是要傳入一個char緩衝區指針,和緩衝區長度,方法至少有四種:

# 方法1 
szPara = create_string_buffer('/0'*100)
dll.PrintInfo(byref(szPara), 100);
print szPara.value
# 方法2
sBuf = 'aaaaaaaaaabbbbbbbbbbbbbb'
pStr = c_char_p( )
pStr.value = sBuf
#pVoid = ctypes.cast( pStr, ctypes.c_void_p ).value
dll.PrintInfo(pStr, len(pStr.value))
print pStr.value
# 方法3
strMa = "/0"*20
FunPrint = dll.PrintInfo
FunPrint.argtypes = [c_char_p, c_int]
#FunPrint.restypes = c_void_p
nRst = FunPrint(strMa, len(strMa))
print strMa,len(strMa)
# 方法4
pStr2 = c_char_p("/0")
print pStr2.value
#pVoid = ctypes.cast( pStr, ctypes.c_void_p ).value
dll.PrintInfo(pStr2, len(pStr.value))
print pStr2.value
1
2
3
4
5
6
7
8
9
10
11
12

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

3、C基本類型和ctypes中實現的類型映射表

ctypes數據類型C數據類型c_charcharc_shortshortc_intintc_longlongc_ulongunsign longc_floatfloatc_doubledoublec_void_pvoid

對應的指針類型是在後面加上”_p”,如int*是c_int_p等等。

在python中要實現c語言中的結構,需要用到類。

4、DLL中的函數返回一個指針。

雖然這不是個好的編程方法,不過這種情況的處理方法也很簡單,其實返回的都是地址,把他們轉換相應的python類型,再通過value屬性訪問。

pchar = dll.getbuffer() 
szbuffer = c_char_p(pchar)

print szbuffer.value
1
2
3

5、處理C中的結構體類型

為什麼把這個單獨提出來說呢,因為這個是最麻煩也是最複雜的,在python裡面申明一個類似c的結構體,要用到類,並且這個類必須繼承自Structure。

先看一個簡單的例子:

C裡面dll的定義如下:

typedef struct _SimpleStruct 
{
int nNo;
float fVirus;
char szBuffer[512];
} SimpleStruct, *PSimpleStruct;
typedef const SimpleStruct* PCSimpleStruct;
extern "C"int __declspec(dllexport) PrintStruct(PSimpleStruct simp);
int PrintStruct(PSimpleStruct simp)
{
printf ("nMaxNum=%f, szContent=%s", simp->fVirus, simp->szBuffer);
return simp->nNo;
}
1
2
3
4
5
6
7
8
9
10
11
12
13

14

Python的定義:

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

上面例子結構體很簡單,但是如果結構體裡面有指針,甚至是指向結構體的指針,處理起來會複雜很多,不過Python裡面也有相應的處理方法,下面這個例子來自網上,本來想自己寫個,懶得寫了,能說明問題就行:

C代碼如下:

typedef struct 
{
char words[10];
}keywords;
typedef struct

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

37
38
39
40
41

Python代碼如下:

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

6、例子

說得天花亂墜,嘿嘿,還是看兩個實際的例子。

例子1:

這是一個GUID生成器,其實很多第三方的python庫已經有封裝好的庫可以調用,不過這得裝了那個庫才行,如果想直接調用一些API,對於python來說,也要藉助一個第三方庫才行,這個例子比較簡單,就是用C++調用win32 API來產生GUID,然後python通過調用C++寫的dll來獲得這個GUID。

C++代碼如下:

extern "C"__declspec(dllexport) char* newGUID(); 
char* newGUID()
{
static char buf[64] = {0};
statc GUID guid;
if (S_OK == ::CoCreateGuid(&guid))
{
_snprintf(buf, sizeof(buf),
"%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
guid.Data1,
guid.Data2,
guid.Data3,
guid.Data4[0], guid.Data4[1],
guid.Data4[2], guid.Data4[3],
guid.Data4[4], guid.Data4[5],
guid.Data4[6], guid.Data4[7]
);
::MessageBox(NULL, buf, "GUID", MB_OK);
}
return (char*)buf;
}
1
2
3
4
5
6
7
8
9
10
11

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

例子2:

這個例子是調用kernel32.dll中的createprocessA函數來啟動一個記事本進程

# -*- coding:utf-8 -*- 
from ctypes import *
# 定義_PROCESS_INFORMATION結構體
class _PROCESS_INFORMATION(Structure):
_fields_ = [('hProcess', c_void_p),
('hThread', c_void_p),
('dwProcessId', c_ulong),
('dwThreadId', c_ulong)]
# 定義_STARTUPINFO結構體

class _STARTUPINFO(Structure):
_fields_ = [('cb',c_ulong),
('lpReserved', c_char_p),
('lpDesktop', c_char_p),
('lpTitle', c_char_p),
('dwX', c_ulong),
('dwY', c_ulong),
('dwXSize', c_ulong),
('dwYSize', c_ulong),
('dwXCountChars', c_ulong),
('dwYCountChars', c_ulong),
('dwFillAttribute', c_ulong),
('dwFlags', c_ulong),
('wShowWindow', c_ushort),
('cbReserved2', c_ushort),
('lpReserved2', c_char_p),
('hStdInput', c_ulong),
('hStdOutput', c_ulong),
('hStdError', c_ulong)]
NORMAL_PRIORITY_CLASS = 0x00000020 #定義NORMAL_PRIORITY_CLASS
kernel32 = windll.LoadLibrary("kernel32.dll") #加載kernel32.dll
CreateProcess = kernel32.CreateProcessA #獲得CreateProcess函數地址
ReadProcessMemory = kernel32.ReadProcessMemory #獲得ReadProcessMemory函數地址
WriteProcessMemory = kernel32.WriteProcessMemory #獲得WriteProcessMemory函數地址
TerminateProcess = kernel32.TerminateProcess
# 聲明結構體
ProcessInfo = _PROCESS_INFORMATION()
StartupInfo = _STARTUPINFO()
fileName = 'c:/windows/notepad.exe' # 要進行修改的文件
address = 0x0040103c # 要修改的內存地址
strbuf = c_char_p("_") # 緩衝區地址
bytesRead = c_ulong(0) # 讀入的字節數
bufferSize = len(strbuf.value) # 緩衝區大小
# 創建進程
CreateProcess(fileName, 0, 0, 0, 0, NORMAL_PRIORITY_CLASS,0, 0, byref(StartupInfo), byref(ProcessInfo))


分享到:


相關文章: