前言
python在很多方面都非常好用,caffe和tensorflow中很多接口都是python的,但是当主程序是C的话,该如何调用呢?这里需要用到boost::python
实现
1.在CMakeLists.txt中包含和python有关的
include_directories(/usr/include /usr/local/include /usr/include/python2.7 /usr/local/cuda-8.0/include)
link_directories(/usr/lib/python2.7 /usr/local/cuda-8.0/lib64 /usr/local/lib)
2.相关代码
//包含boost::python头文件
#include <boost/python.hpp>
namespace bp = boost::python;
Py_Initialize(); //在C++程序里初始化python
bp::object sys = bp::import("sys");
sys.attr("path").attr("append")(boost::python::str("your path")); //python脚本所在的路径
bp::object os = bp::import("os");
bp::object py_test = bp::import("py_test"); //python脚本的名字
bp::str model_path("your model path"); //模型路径
bp::object model = py_test.attr("get_model")(model_path); //get_model为python脚本中的函数名,同理调用python脚本中其他函数