
ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.
ctypes是Python的外部函数库。它提供了C兼容的数据类型,并且允许调用动态链接库/共享库中的函数。它可以将这些库包装起来给Python使用。
在使用Python开发应用程序的时候,往往不可避免的需要用到其他语言编写的库中的函数,例如需要C语言库做一些效率上的补充,或者不同语言系统间做数据交互。使用python中的ctypes库可以很方便的调用windows的dll或linux下的so文件。
现在来简单的介绍一下ctypes的用法。
1.引入ctypes库
1 |
from ctypes import * |
2.假设有了一个用于做加法的DLL(add.dll),该DLL有一个符合cdecl调用约定(这里强调调用约定是因为,stdcall调用约定和cdecl调用约定声明的导出函数,在使用python加载时使用的加载函数是不同的)的导出函数Add。
1 2 3 4 5 |
from ctypes import * dll = CDLL("add.dll") print dll.Add(1, 102) #Output is 103. |