Python調用C/C++程序


編程中會遇到調用其他語言到庫,這里記錄一下Python調用C++。

Python底層是C, 所以調用C還是比較方便。調用C++有些麻煩。

Python提供了ctypes, 方便將Python類型轉為C類型,實現傳參數、函數返回類型的對應。ctypes網址:https://docs.python.org/2/library/ctypes.html

 

使用Python調用C/C++主要有三步:

(1) 編寫好C/C++函數

(2) 把C/C++函數打包成庫文件

(3) Python加載庫文件並調用


代碼記錄一下:

1. pycall.h

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 class PythonTest{
 6 public:
 7     PythonTest():_is_inited(false), _num(0){
 8     
 9     }   
10 
11     int init(int num){
12         _num = num;
13         _is_inited = true;
14         printf("inited ok\n");
15         return 0;
16     }   
17     
18     int str2(char *src, char* dest, int len){
19         if (src == NULL || len <= 0){ 
20             return 0;
21         }   
22 
23         int src_len = strlen(src);
24         int num = snprintf(dest, len, "%s%s", src, src);
25         return (num < len -1)? num:0;
26     }   
27 
28     bool is_inited(){
29         printf("_num = %d\n", _num);
30         return _is_inited;
31     }   
32 
33 private:
34     bool _is_inited;
35     int _num;
36 };

 2. pycall_so.cpp

 1 #include "pycall.h"
 2 
 3 extern "C" {
 4 
 5 PythonTest py; 
 6 
 7 int init(int num){
 8     return py.init(num);
 9 }
10 
11 bool is_inited(){
12     return py.is_inited();
13 }
14 
15 int str2(char* src, char* dest, int len){
16     return py.str2(src, dest, len);
17 }
18 
19 int add(int a, int b){ 
20     return a + b;
21 }
22 
23 }

 3. pycall.py

 1 #coding=utf-8
 2 
 3 import ctypes 
 4 from ctypes import *
 5 
 6 ##加載庫文件
 7 ll = ctypes.cdll.LoadLibrary  
 8 lib = ll("./libpycall.so")   
 9 
10 ##call
11 fun=lib.init    ###類似C/C++函數指針
12 fun.restype = c_int ##設置函數返回值類型
13 print fun(8);
14 print "*" * 20
15 
16 ##call
17 fun=lib.is_inited
18 fun.restype = c_bool
19 print fun();
20 print "*" * 20
21 
22 ##call
23 fun=lib.str2
24 src = "hello world "
25 dest = "*" * 30     ###申請buf, 用於保存返回結果 
26 num = fun(src, dest, len(dest)) ###傳遞指針作為參數
27 if num != 0:
28     print dest[:num]
29 else:
30     print "buf is not ok"
31 print "*" * 20
32 
33 ##call
34 print lib.add(1, 2); 
35 print "*" * 20

 執行結果:

 


免責聲明!

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



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