python中調用C++寫的動態庫


一、環境:Windows XP + Python3.2

1. dll對應的源文件(m.cpp):

 

[cpp]  view plain copy
 
  1. #include <stdio.h>  
  2.   
  3. extern "C"  
  4. {  
  5.     _declspec(dllexport) int add(int a, int b)  
  6.     {  
  7.         return a+b;  
  8.     }  
  9.   
  10.     _declspec(dllexport) void print_sum(unsigned long ulNum)  
  11.     {  
  12.         while(ulNum != 0)  
  13.         {  
  14.             printf("The ulNum is : %u\n", ulNum--);  
  15.         }  
  16.     }  
  17. }  


2. python源程序:

 

[python]  view plain copy
 
  1. # coding=GBK  
  2.   
  3. from ctypes import *  
  4. import time  
  5.   
  6. if __name__ == '__main__':  
  7.     time_begin = time.clock()  
  8.   
  9.     #dll = CDLL("d.dll")            # 加載dll方式一  
  10.     dll = cdll.LoadLibrary("d.dll") # 加載dll方式二  
  11.     print(dll.add(2, 6))            # 調用dll中add方法  
  12.     dll.print_sum(100)              # 調用dll中print_sum方法  
  13.   
  14.     t = time.clock() - time_begin   # 計算時間差  
  15.     print("Use time: %f" %t)        # 打印耗時時間  


運行輸出:

 

 

[plain]  view plain copy
 
  1. E:\Program\Python>del  
  2. 8  
  3. The ulNum is : 100  
  4. The ulNum is : 99  
  5. The ulNum is : 98  
  6. ...........  
  7. The ulNum is : 2  
  8. The ulNum is : 1  
  9. Use time: 0.003853  
  10.   
  11. E:\Program\Python>  

 

二、環境:Fedora12 + Python2.6

1. 動態庫源文件(a.cpp):

 

[cpp]  view plain copy
 
  1. #include <stdio.h>  
  2.   
  3. extern "C"  
  4. {  
  5.     int add(int a, int b)  
  6.     {  
  7.         return a+b;  
  8.     }  
  9.   
  10.     void print_sum(unsigned long ulNum)  
  11.     {  
  12.         while(ulNum != 0)  
  13.         {  
  14.             printf("The ulNum is : %u\n", ulNum--);  
  15.         }  
  16.     }  
  17. }  


編譯指令:g++ -shared -o liba.so a.cpp

 

2. python源程序(del.py):

 

[python]  view plain copy
 
  1. #!/usr/bin/env python  
  2. # coding=UTF-8  
  3.   
  4. from ctypes import *  
  5. import time  
  6.   
  7. if __name__ == '__main__':  
  8.     time_begin = time.clock()  
  9.   
  10.     dll = CDLL("./liba.so")                 # 加載dll方式一(默認在系統lib庫路徑下查找.so文件)  
  11.     #dll = cdll.LoadLibrary("./liba.so")    # 加載dll方式二  
  12.     print(dll.add(2, 6))                    # 調用dll中add方法  
  13.     dll.print_sum(10000)                    # 調用dll中print_sum方法  
  14.   
  15.     t = time.clock() - time_begin           # 計算時間差  
  16.     print("\nUse time: %s" %t)              # 打印耗時時間  


運行結果:與windows版本基本相同!

 

 

結論:Linux上用Python加載動態庫時默認是從系統lib路徑下是查找庫文件的。所以在python中加載當前路徑下的動態庫的話,路徑要寫“./liba.so",否則會提示動態庫文件找不到!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM