- 0
- 0
- 约6.49千字
- 约 9页
- 2019-12-23 发布于湖北
- 举报
Python:使用ctypes库调用外部DLL
Python之ctypes
ctypes是Python的一个外部库,提供和C语言兼容的数据类型,可以很方便地调用C DLL中的函数。在Python2.5官方安装包都带有ctypes 1.1版。ctypes的官方文档在这里。
ctypes的使用非常简明,如调用cdecl方式的DLL只需这样:
view sourceprint?1 from ctypes import *;
2 h=CDLL(msvcrt.dll)
3 h.printf(a=%d,b=%d,a+b=%d,1,2,1+2);
以上代码运行后输出 a=1,b=2,a+b=3。
加载库和普通函数的调用
官方API提供的库中有几个主要的函数:
view sourceprint?01 //初始化
02 int DCSPCLIENTDLL InitInterface( const char *pCenterIP, const unsigned short nUpLinkSvrPort,const unsigned short nDownLinkSvrPort );
03
04 //释放资源
05 int DCSPCLIENTDLL FiniInterface( void );
06
07 //登录
08 int DCSPCLIENTDLL Login( const unsigned int uiBranchPlatformID, const unsigned int nUserID, const char *pPassword );
09 //注销
10 int DCSPCLIENTDLL Logout( const unsigned int uiBranchPlatformID, const unsigned int nUserID, const char *pPassword );
11
12 //发车辆实时定位数据
13 int DCSPCLIENTDLL SendUPRealLocation( const char * const pDeviceId, const char cDeviceColor,
14 const unsigned short nMsgCode, const _stBPDynamicData * const pStGpsData );
在Python中加载使用:
view sourceprint?01 from ctypes import *
02
03 #加载API库
04 api = CDLL(DCSPClientDLL.dll);
05 #初始化函数的参数类型
06 api.InitInterface.argtypes=[c_char_p,c_ushort,c_ushort]
07 api.Login.argtypes=[c_uint,c_uint,c_char_p]
08 api.Logout.argtypes=[c_uint,c_uint,c_char_p]
09
10 #初始化并登录
11 api.InitInterface(u中心服务器地址 , u上行服务端端口 , u下行客户端端口)
12 api.Login(platformID,userID,password);
13 #.....其它操作
14 api.Logout(platformID,userID,password); #注销
参数类型可以像上面的代码一样预先设定好,或者在调用函数时再把参数转成相应的c_***类型。ctypes的类型对应如下:
如此,完成了简单的第一步。
C语言中的Struct数据结构
在发送实时定位数据的函数SendUPRealLocation中有一个参数是结构体类型 _stBPDynamicData。python中没有struct这种数据结构,ctypes很周全,对C的struct和union这二种数据类型都提供很好的支持。stBPDynamicData结构的定义如下:
view sourceprint?01 // 车辆动态数据结构体
02 struct _stBPDynamicData
03 {
04 // 加密状态
05 unsigned char encrypt;
06 // GPS 时间
07 _StructTime gpsTime;
08 // 经度
09 unsigned int longitude;
10
您可能关注的文档
最近下载
- 特定技能2号农业练习题11.docx
- 2026年在带头固本培元、增强党性等五个带头方面对照检查存在的问题、整改措施材料6份文.docx VIP
- 冰川雪山攀登技巧心得分享心得总结.docx VIP
- 小森印刷机s40操作说明.pdf VIP
- 8篇2026年带头固本培元、增强党性(五个带头)方面存在的问题精选.docx VIP
- 翼状胬肉病人护理精品PPT课件.pptx
- 2026年河北省职业病诊断医师资格(尘肺病类)高分突破必练试题库(含答案).docx
- 2024中医临床实践指南穴位埋线减肥.docx VIP
- 人教PEP版五年级下册英语全册教案(单元整体教学设计).docx VIP
- 2025年贵州省公务员考试题及答案解析.docx
原创力文档

文档评论(0)