分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.youkuaiyun.com/jiangjunshow
也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!
本文以实例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.ig++ -c -fPIC rachel_wrap.cxx -I/home/zhangruiqing01/.jumbo/include/python2.7 -I./includeg++ -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
最后看一下本文中程序的结构:
给我老师的人工智能教程打call!http://blog.youkuaiyun.com/jiangjunshow
本文详细介绍使用SWIG工具从Python调用C++代码的方法,包括无参数传递和带参数传递的场景,通过实例演示了如何搭建环境并实现跨语言调用。

被折叠的 条评论
为什么被折叠?



