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\n", 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值