网上收集的,综合各种方案,找到的boost python最简单方式,python调用c++
1 安装 boost:
apt-cache search boost
apt-get install libboost-all-dev
2 安装anaconda
这个自己去下载后sh就可以。要点是在/ect/profile增加c++寻找h文件目录:
export PATH=/root/anaconda3/bin:$PATH
export CPLUS_INCLUDE_PATH="$CPLUS_INCLUDE_PATH:/root/anaconda3/include/python3.7m"
3 软连接改变动态链接库名字
cd /usr/lib/x86_64-linux-gnu
sudo ln -s libboost_python-py35.so libboost_python3.so
连接是py35的,其实37也可以。
## 4 编译动态链接
c++代码:
#include<string>
#include<boost/python.hpp>
using namespace std;
using namespace boost::python;
class World {
public:
void set(string msg) { this->msg = msg; }
string greet(string str) { return str; }
string msg;
};
BOOST_PYTHON_MODULE(hello) //导出的module 名字
{
class_<World>("World")
.def("greet", &World::greet)
.def("set", &World::set);
}
g++ main.cpp -shared -fPIC -o hello.so -lboost_python3
5 python引用
Import hello等,自己可以百度相关的c++文件和python文件,这些不是难点。
import hello
planet = hello.World()
planet.set("howdy")
print (planet.greet("asjdfalkjdfa"))
亲测传递string,返回string有效,这对我的场景就够了,能string就能json。
本文详细介绍了使用Boost.Python在Python中调用C++代码的步骤。从安装Boost和Anaconda开始,到创建软链接、编译动态链接库,最后在Python中引用并测试字符串传递与返回功能。
4190

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



