您的位置:首页 > 编程语言 > C语言/C++

使用python的内置ctypes模块与c、c++写的dll进行交互

2011-12-13 15:39 746 查看

调用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)


运行结果预览

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: