一、环境:Windows XP + Python3.2
1. dll对应的源文件(m.cpp):
#include <stdio.h> extern "C" { _declspec(dllexport) int add(int a, int b) { return a+b; } _declspec(dllexport) void print_sum(unsigned long ulNum) { while(ulNum != 0) { printf("The ulNum is : %u\n", ulNum--); } } }
2. python源程序:
# coding=GBK from ctypes import * import time if __name__ == '__main__': time_begin = time.clock() #dll = CDLL("d.dll") # 加载dll方式一 dll = cdll.LoadLibrary("d.dll") # 加载dll方式二 print(dll.add(2, 6)) # 调用dll中add方法 dll.print_sum(100) # 调用dll中print_sum方法 t = time.clock() - time_begin # 计算时间差 print("Use time: %f" %t) # 打印耗时时间
运行输出:
E:\Program\Python>del 8 The ulNum is : 100 The ulNum is : 99 The ulNum is : 98 ........... The ulNum is : 2 The ulNum is : 1 Use time: 0.003853 E:\Program\Python>
二、环境:Fedora12 + Python2.6
1. 动态库源文件(a.cpp):
#include <stdio.h> extern "C" { int add(int a, int b) { return a+b; } void print_sum(unsigned long ulNum) { while(ulNum != 0) { printf("The ulNum is : %u\n", ulNum--); } } }
编译指令:g++ -shared -o liba.so a.cpp
2. python源程序(del.py):
#!/usr/bin/env python # coding=UTF-8 from ctypes import * import time if __name__ == '__main__': time_begin = time.clock() dll = CDLL("./liba.so") # 加载dll方式一(默认在系统lib库路径下查找.so文件) #dll = cdll.LoadLibrary("./liba.so") # 加载dll方式二 print(dll.add(2, 6)) # 调用dll中add方法 dll.print_sum(10000) # 调用dll中print_sum方法 t = time.clock() - time_begin # 计算时间差 print("\nUse time: %s" %t) # 打印耗时时间
注意:Linux上用Python加载动态库时默认是从系统lib路径下是查找库文件的。所以在python中加载当前路径下的动态库的话,路径要写“./liba.so",否则会提示动态库文件找不到!
http://blog.csdn.net/joeblackzqq/article/details/7405992
http://blog.csdn.net/magictong/article/details/3075478(更详细的说明)
http://blog.csdn.net/oracleot/article/details/3851512(使用SWIG实现C++导出python接口的配置)