使用boost實現c++與python的相互調用

學習boost.python 模塊,我的環境windows上qt5.5 mingw4.92, 設置好環境變量。
1.環境搭建:在python已安裝的包裏面有一個include文件夾 裏面存放的是需要的頭文件,libs文件夾 裏面存放的是需要的庫文件,若想調用這裏面的庫 可以用ide工具把頭文件和庫文件路徑都指定一下,這樣就可以被boost.python 調用 了

2.生成動態庫:我是用qt creator來創建的 , 最終生成的是dll文件 我發現dll文件無法直接被import 於是嘗試把dll文件改成.pyd後綴的文件, 就可以執行了
生成的庫文件

修改之後存放到python的目錄下面

執行python hello.py



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;
}



c++擴展python

#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())



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章