ctypes使得python能够直接调用c语言开发的动态链接库,非常强大。
为了使用CTypes,你必须依次完成以下步骤:
* 编写动态连接库程序
* 载入动态连接库
* 将Python的对象转换为ctypes所能识别的参数
* 使用ctypes的参数调用动态连接库中的函数
一、Windows下使用Python的ctypes调用Dll动态链接库
- 编写dll文件
打开VS2008,新建一个VC工程,选择Win32类型,Win32项目,用程序类型选择DLL………
调用方式见Linux调用方式。
二、Linux下使用Python的ctypes调用so动态链接库
- 编写so文件
- Python调用so动态链接库
//test.h #include "stdio.h" void test(); float add(float, float);
//test.c #include "test.h" void test() { printf("Hello Dll...\n"); } float add(float a, float b) { return a + b; }
gcc -fPIC -shared test.c -o libtest.so #-fPIC 编译成位置无关代码,必须 不然你的程序在别的地方肯可能运行不了 #-shared 当然是说要编译成共享库了
#!/usr/bin/env python # -*-coding:UTF-8-*- print "sss" from ctypes import * test = cdll.LoadLibrary("./libtest.so") test.test() add = test.add add.argtypes = [c_float, c_float] # 参数类型,两个float(c_float内ctypes类型) add.restype = c_float print add(1.2, 19.2)
发
发的