歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python 調用 C++ 實例代碼

Python 調用 C++ 實例代碼

日期:2017/3/1 9:14:50   编辑:Linux編程

本文以實例code講解Python 調用 C++的方法。
1. 如果沒有參數傳遞從python傳遞至C++,python調用C++的最簡單方法是將函數聲明為C可用函數,然後作為C code被python調用,如這裡三樓所示;
2. 有參數傳遞至C++函數,swig是最便捷的調用方法,以下面這個工程所示為例;

rachel.i (swig文件):

%module rachel
%{
#include "rachel.h"
%}

extern int linear(int x, int w, int b);

C++ code 部分:

rachel.h:

#include<stdio.h>                 
#include<Python.h>                

int linear(int x, int w, int b);  

rachel.cpp:

#include "rachel.h"       

int linear(int x, int w, int b){ 
    int res = w * x + b;         
    printf("%d\n", res);         
    return res;                  
}                                

執行命令:

swig -c++ -python rachel.i
g++ -c -fPIC rachel_wrap.cxx -I/home/zhangruiqing01/.jumbo/include/python2.7 -I./include
g++ -shared rachel.o rachel_wrap.o -o _rachel.so

第一句swig生成rachel_warp.cxx (如果是C,則用swig -python rachel.i生成rachel_warp.c文件);
最後一句生成動態鏈接庫_rachel.so供python調用(如果是C,則用ld -shared rachel.o rachel_warp.o -o _rachel.so);

python 調用部分:

>>> import _rachel
>>> _rachel.linear(1,2,5)
7

最後看一下本文中程序的結構:


CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved