使用python的内置ctypes模块与c、c++写的dll进行交互
调用C编写的动态链接库
代码示例
from ctypes import *
dll = CDLL("add.dll")#加载cdecl的dll。另外加载stdcall的dll的方式是WinDLL("dllpath")
sum=dll.Add(1, 102)
若参数为指针
p=1
sum=dll.sub(2, byref(p))#通过库中的byref关键字来实现
若参数为结构体
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()
dll.test(byref(o))
print (o.kws[0].words)
print (o.kws[1].words)
print (o.len)
调用Windows API
#导入ctypes模块
from ctypes import *
windll.user32.MessageBoxW(0, '内容!', '标题', 0)
#也可以用以下方式为API函数建立个别名后再进行调用
MessageBox = windll.user32.MessageBoxW
MessageBox(0, '内容!', '标题', 0)
摘自 随心追求!
补充:Web开发 , Python ,