2024年2月8日发(作者:)
Python调用windows下DLL详解
原文URL是/magictong/archive/2008/10/14/
貌似原文的网页服务器有问题,总是load不全,所以备个份:
Python调用windows下DLL详解
在python中某些时候需要C做效率上的补充,在实际应用中,需要做部分数据的交互。使用python中的ctypes模块可以很方便的调用 windows的dll(也包括linux下的so等文件),下面将详细的讲解这个模块(以windows平台为例子),当然我假设你们已经对 windows下怎么写一个DLL是没有问题的。
引入ctypes库
from ctypes import *
假设你有了一个符合cdecl(这里强调调用约定是因为,stdcall调用约定和cdecl调用约定声明的导出函数,在用python加载使用的加载函数是不同的,后面会说明)调用约定的DLL(名字是),且有一个导出函数Add。
建立一个Python文件测试:
from ctypes import *
dll = CDLL("")
print (1, 102)
结果:103
上面是一个简单的例子。
1、加载DLL
上面已经说过,加载的时候要根据你将要调用的函数是符合什么调用约定的。
stdcall调用约定:两种加载方式
Objdll = brary("dllpath")
Objdll = ("dllpath")
cdecl调用约定:也有两种加载方式
Objdll = brary("dllpath")
Objdll = ("dllpath")
其实windll和cdll分别是WinDLL类和CDll类的对象。
2、调用dll中的方法
在1中加载dll的时候会返回一个DLL对象(假设名字叫Objdll),利用该对象就可以调用dll中的方法。
e.g.如果dll中有个方法名字叫Add(注意如果经过stdcall声明的方法,如果不是用def文件声明的导出函数的话,编译器会对函数名进行修改,这个要注意)
调用:nRet = (12, 15) 即完成一次调用。
看起来调用似乎很简单,不要只看表象,呵呵,这是因为Add这个函数太简单了,现在假设函数需要你传入一个int类型的指针(int*),可以通过库中的byref关键字来实现,假设现在调用的函数的第三个参数是个int类型的指针。
intPara = c_int(9)
(23, 102, byref(intPara))
如果是要传入一个char缓冲区指针,和缓冲区长度,方法至少有四种:
# char* -- 1
szPara = create_string_buffer('0'*100)
nfo(byref(szPara), 100);
# char* -- 2
sBuf = 'aaaaaaaaaabbbbbbbbbbbbbb'
pStr = c_char_p( )
= sBuf
#pVoid = ( pStr, ctypes.c_void_p ).value
nfo(pStr, len())
# char* -- 3
strMa = "0"*20
FunPrint = nfo
es = [c_char_p, c_int]
#es = c_void_p
nRst = FunPrint(strMa, len(strMa))
print strMa,len(strMa)
# char* -- 4
pStr2 = c_char_p("0")
#pVoid = ( pStr, ctypes.c_void_p ).value
nfo(pStr2, len())
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属性访问。
pchar = fer()
szbuffer = c_char_p(pchar)
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;
}
Python的定义:
from ctypes import *
class SimpStruct(Structure):
_fields_ = [ ("nNo", c_int),
("fVirus", c_float),
("szBuffer", c_char * 512)]
dll = CDLL("")
simple = SimpStruct();
= 16
= 3.1415926
er = "magicTong0"
print truct(byref(simple))
上面例子结构体很简单,如果结构体里面有指针,甚至是指向结构体的指针,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;
}
Python代码如下:
class keywords(Structure):
_fields_ = [('words', c_char *10),]
class outStruct(Structure):
_fields_ = [('kws', POINTER(keywords)),
('len', c_int),]
o = outStruct()
(byref(o))
print [0].words;
print [1].words;
6、例子
说得天花乱坠,嘿嘿,还是看两个实际的例子。
例子一:
这是一个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))
{
// "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X"
_snprintf(buf, sizeof(buf),
"%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
1,
2,
3,
4[0], 4[1],
4[2], 4[3],
4[4], 4[5],
4[6], 4[7]
);
::MessageBox(NULL, buf, "GUID", MB_OK);
}
return (char*)buf;
}
Python代码如下:
def CreateGUID():
"""
创建一个全局唯一标识符
类似:E06093E2-699A-4BF2-A325-4F1EADB50E18
NewVersion
"""
try:
# dll path
strDllPath = [0] + str() + ""
dll = CDLL(strDllPath)
b = D()
a = c_char_p(b)
except Exception, error:
print error
return ""
return
例子二:
这个例子是调用中的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 = brary("") # 加载
CreateProcess = ProcessA # 获得CreateProcess函数地址
ReadProcessMemory = ocessMemory # 获得ReadProcessMemory函数地址
WriteProcessMemory = rocessMemory # 获得WriteProcessMemory函数地址
TerminateProcess = ateProcess
# 声明结构体
ProcessInfo = _PROCESS_INFORMATION()
StartupInfo = _STARTUPINFO()
fileName = 'c:/windows/' # 要进行修改的文件
address = 0x0040103c # 要修改的内存地址
strbuf = c_char_p("_") # 缓冲区地址
bytesRead = c_ulong(0) # 读入的字节数
bufferSize = len() # 缓冲区大小
# 创建进程
CreateProcess(fileName, 0, 0, 0, 0, NORMAL_PRIORITY_CLASS,0, 0, byref(StartupInfo),
byref(ProcessInfo))
Python调用Dll的几个例子
from ctypes import *
fileName=""
func=brary(fileName)
#print orld()
orld()
(Lib.h)
#ifndef LIB_H
#define LIB_H
extern "C" int __declspec(dllexport)add(int x, int y);
#endif
()
#include "Lib.h"
int add(int x, int y)
{
return x + y;
}
编译为。
然后建立一个Python文件测试:
from ctypes import *
dll = CDLL("")
print (1, 1)
结果:2
简单得不能再简单了!
from ctypes import *
fileName=""
func=brary(fileName)
import
#usedll=ch("")
搞定了几个东西
1,取得鼠标位置,get_mpos()
2,移动鼠标,set_mpos()
3,鼠标左键点击,move_click()
4,键盘输入(部分搞定,那个scancode还不明白是啥意思,为什么0x99输出的是字符'p'???)
代码如下
[code]
from ctypes import *
import time
#
win_start = (9, 753)
close_window = (1017, 4)
#
PUL = POINTER(c_ulong)
class KeyBdInput(Structure):
_fields_ = [("wVk", c_ushort),("wScan", c_ushort),("dwFlags",
c_ulong),("time", c_ulong),("dwExtraInfo", PUL)]
class HardwareInput(Structure):
_fields_ = [("uMsg", c_ulong),("wParamL", c_short),("wParamH", c_ushort)]
class MouseInput(Structure):
_fields_ = [("dx", c_long),("dy", c_long),("mouseData", c_ulong),("dwFlags",
c_ulong),("time",c_ulong),("dwExtraInfo", PUL)]
class Input_I(Union):
_fields_ = [("ki", KeyBdInput),("mi", MouseInput),("hi", HardwareInput)]
class Input(Structure):
_fields_ = [("type", c_ulong),("ii", Input_I)]
class POINT(Structure):
_fields_ = [("x", c_ulong),("y", c_ulong)]
#
def get_mpos():
orig = POINT()
sorPos(byref(orig))
return int(orig.x), int(orig.y)
#
#
def set_mpos(pos):
x,y = pos
sorPos(x, y)
#
#
def move_click(pos, move_back = False):
origx, origy = get_mpos()
set_mpos(pos)
FInputs = Input * 2
extra = c_ulong(0)
ii_ = Input_I()
ii_.mi = MouseInput( 0, 0, 0, 2, 0, pointer(extra) )
ii2_ = Input_I()
ii2_.mi = MouseInput( 0, 0, 0, 4, 0, pointer(extra) )
x = FInputs( ( 0, ii_ ), ( 0, ii2_ ) )
put(2, pointer(x), sizeof(x[0]))
if move_back:
set_mpos((origx, origy))
return origx, origy
#
def sendkey(scancode, pressed):
FInputs = Input * 1
extra = c_ulong(0)
ii_ = Input_I()
flag = 0x8 # KEY_SCANCODE
ii_.ki = KeyBdInput( 0, 0, flag, 0, pointer(extra) )
InputBox = FInputs( ( 1, ii_ ) )
if scancode == None:
return
InputBox[0]. = scancode
InputBox[0].s = 0x8 # KEY_SCANCODE
if not(pressed):
InputBox[0].s |= 0x2 # released
put(1, pointer(InputBox), sizeof(InputBox[0]))
if pressed:
print "%x pressed" % scancode
else:
print "%x released" % scancode
if __name__ == '__main__':
origx, origy = get_mpos()
print 'Orig Pos:', origx, origy
#set_mpos(9, 753)
#move_click(win_start)
move_click((800,600))
(1)
sendkey(0x99,1)
#keyboard_input()
#set_mpos(origx, origy)
Python调用C的DLL
最近研究这个,准备在新部门里大用Python了
首先用VC建立一个试验用的DLL。
假设函数的参数是这样的
typedef struct _TASK_PARAM
{
int nTaskPriority;
int nMaxNum;
CHAR szContent[512];
_TASK_PARAM::_TASK_PARAM()
{
ZeroMemory(this, sizeof(*this));
}
} TASK_PARAM, *PTASK_PARAM;
typedef CONST TASK_PARAM* PCTASK_PARAM;
函数如下:
extern "C" int Test(PCTASK_PARAM para)
_39_181_Closed_Image" style="DISPLAY: none" onclick="y='none';
mentById('_39_181_Closed_Text').y='none';
mentById('_39_181_Open_Image').y='inline';
mentById('_39_181_Open_Text').y='inline';" alt=""
align="top"
src="/syntaxhighlighting/OutliningIndicators/" />{
printf ("nTaskPriority=%d, nMaxNum=%d, szContent=%s",para->nTaskPriority,para->nMaxNum,para->szContent);
return para->nTaskPriority;
}
Python里首先这样声明对应的对象:
class TASK_PARAM(Structure):
_fields_ = [ ("nTaskPriority", c_int),
("nMaxNum", c_int),
("szContent", c_char * 512)]
然后这样调用:
brary("C:");
para = TASK_PARAM();
riority = 1;
m = 2;
fyContent = '中文0';
print fyContent
(byref(para));
如果VC的函数里要修改Python传入的参数,例如:
extern "C" int TestIntRef(int* para)
{
*para = *para + 1;
return *para;
}
Python里就这么玩:
intPara = c_int(9)
print tRef(byref(intPara));
print ;
对于这种要修改字符串的:
extern "C" int TestCharRef(char* para)
R-LEFT: #808080 1px solid; BORDER-BOTTOM: #808080 1px solid; BACKGROUND-COLOR:
#ffffff">...{
strcpy(para, "char* test.");
return 2;
}
也不在话下:
szPara = create_string_buffer('0' * 64)
print arRef(byref(szPara));
print ;
都是从Python的ctypes的教程看来的。之前要from ctypes import*,好玩
python调用dll方法
收藏
在python中调用dll文件中的接口比较简单,实例代码如下:
如我们有一个文件,内部定义如下:
extern "C"
{
int __stdcall test( void* p, int len)
{
return len;
}
}
在python中我们可以用以下两种方式载入
1.
import ctypes
dll = brary( '' )
2.
import ctypes
dll = ( '' )
其中为类的一个对象,已经在ctypes模块中定义好的。在中有test接口,可直接用dll调用即可
nRst = ( )
print nRst
由于在test这个接口中需要传递两个参数,一个是void类型的指针,它指向一个缓冲区。一个是该缓冲区的长度。因此我们要获取到python中的字符串的指针和长度
#方法一:
sBuf = 'aaaaaaaaaabbbbbbbbbbbbbb'
pStr = ctypes.c_char_p( )
= sBuf
pVoid = ( pStr, ctypes.c_void_p ).value
nRst = ( pVoid, len( ) )
#方法二:
test =
es = [ctypes.c_char_p, ctypes.c_int]
es = ctypes.c_int
nRst = test(sBuf, len(sBuf))
如果修改中接口的定义如下:
extern "C"
{
int __cdecl test( void* p, int len)
{
return len;
}
}
由于接口中定义的是cdecl格式的调用,所以在python中也需要用相应的类型
1.
import ctypes
dll = brary( '' )
##注:一般在linux下为test.o文件,同样可以使用如下的方法:
## dll = brary('test.o')
2.
import ctypes
dll = ( '' )
本文发布于:2024-02-08 08:29:07,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170735214767052.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |