python 调用 C++ code

本文以实例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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

C++ code 部分:

rachel.h:

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

int linear(int x, int w, int b);  
  • 1
  • 2
  • 3
  • 4

rachel.cpp:

#include "rachel.h"       

int linear(int x, int w, int b){ 
    int res = w * x + b;         
    printf("%d
", res);         
    return res;                  
}                                
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

执行命令:

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
  • 1
  • 2
  • 3
  • 4

第一句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
  • 1
  • 2
  • 3

最后看一下本文中程序的结构: 


这里写图片描述 
 
 
from: http://blog.csdn.net/abcjennifer/article/details/49374307
原文地址:https://www.cnblogs.com/GarfieldEr007/p/5354567.html