python调用dll动态库

来源:互联网 发布:淘宝杜蕾斯授权店 编辑:程序博客网 时间:2024/06/06 03:40

python调用动态库有两种类型,主要看dll的导出函数的调用约定:__stdll和__cdecl

对应的动态库的调用方式为

ctypes.cdll.LoadLibrary( 'test.dll' )对应__cdecl调用方式

ctypes.windll.LoadLibrary( 'test.dll' )对应_stdll调用方式


test.h文件

#include <stdio.h>
#include <wchar.h>


//因为给python测试,默认不给c\c++程序调用,所以直接写__declspec(dllexport),如果要给c\c++调用,需要自己定义宏决定__declspec(dllexport)是导入还是导出



extern "C"
{
__declspec(dllexport) int __cdecl test(wchar_t* a, int len);

};


test.cpp文件

#include "test.h"

__declspec(dllexport) int __cdecl test(wchar_t* a, int len)
{
printf("get [%S] len %d\r\n", a, len);
printf("hell test %s line %d \r\n", __FUNCTION__, __LINE__);


return 169;
}


调用动态库的test.py文件

#coding=utf-8

import ctypes

slen = 4

sBuf = 'aaaaaaaaaabbbbbbbbbbbbbb'
 
adll = ctypes.cdll.LoadLibrary( 'pydll.dll' )


##传入的参数是宽字符
adll.test(sBuf, 123);

input("press enter to quit")  


如果调用方式不匹配可能报ValueError: Procedure probably called with too many arguments (8 bytes in excess)错误




0 0