学习boost.python 模块,我的环境windows上qt5.5 mingw4.92, 设置好环境变量。
1.环境搭建:在python已安装的包里面有一个
include文件夹 里面存放的是需要的头文件,
libs文件夹
里面存放的是需要的库文件,
若想调用这里面的库 可以用ide工具把头文件和库文件路径都指定一下,
这样就可以被
boost.python
调用 了
2.生成动态库:我是用qt creator来创建的 , 最终生成的是dll文件 我发现dll文件无法直接被import 于是尝试把dll文件
改成.pyd后缀的文件, 就可以执行了
生成的库文件
修改之后存放到python的目录下面
cpu直接超过80%了, python调用c++的库可以充分使用多核
附上代码:
c++调用python的方法
#include <iostream>
#include <python27/Python.h>
#include <boost/python.hpp>
#include <iostream>
#include <string>
#include <string.h>
#include <fstream>
using namespace std;
using namespace boost::python;
int main() {
//初始化读取 py 文件的信息
std::ifstream fin;
fin.open("D:/py_test/test.py");
std::string str;
std::string str_in = "";
while (getline(fin, str)) //一行一行地读到字符串str_in中
{
str_in = str_in + str + '\n';
}
fin.close();
cout<<str_in<<endl;
Py_Initialize();
// PyRun_SimpleString("from time import time,ctime\n"
// "print 'Today is',ctime(time())\n");
PyRun_SimpleString(str_in.c_str());
Py_Finalize();
cout<<"it is over ...."<<endl;
return 0;
}
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <iostream>
//头文件是我自己设置的位置
#include <python27/Python.h>
#include <boost/python.hpp>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>
using namespace std;
using namespace boost;
using namespace boost::python;
void test(){
string sum;
while(1)
{
string ss = "111111112222222";
sum = sum + ss;
}
}
char const* greet()
{
thread_group group;
for(int num=0;num<10;num++)
group.create_thread(bind(test));
group.join_all();
return "hello, world";
}
BOOST_PYTHON_MODULE(hello_world)
{
using namespace boost::python;
def("greet", greet);
}
python测试代码
#! /usr/bin/env python
# Copyright Joel de Guzman 2002-2007. Distributed under the Boost
# Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt
# or copy at http://www.boost.org/LICENSE_1_0.txt)
# Hello World Example from the tutorial
import hello_world
print(hello_world.greet())