c++調用python

來源:互聯網
上載者:User

標籤:python   c++   

1、下載boost1.52,http://www.boost.org/,解壓檔案到d:\boost\boost_1_52_0;

2、下載python2.7.3,http://www.python.org/;(boost1.4支援到python2.5)

3、安裝python,我安裝在了D:\Python25,設定環境變數PATH D:\Python25;

4、開始->程式->Microsoft Visual Studio 2010->Visual Studio Tools->Visual Studio 命令提示(2010),開啟一個控制台

5、在控制台依次輸入下面3行:

cd d:\boost\boost_1_49_0
bootstrap.bat
bjam stage –toolset=msvc-9.0 –with-python –stagedir=”D:\boost_1_49_0\bin\vc9” link=static runtime-link=shared runtime-link=static threading=multi debug release

6、項目屬性中配置如下
連結器裡的附加庫目錄加入,python/libs(python的安裝目錄中),boost/vs2010/lib(產生的boost的目錄中)

c/c++的附加庫目錄加入,boost(boost的下載目錄),python/include(python的安裝目錄)

1、確認工程中項目屬性中配置如下
連結器裡的附加庫目錄加入,python/libs(python的安裝目錄中),boost/vs2010/lib(產生的boost的目錄中)
c/c++的附加庫目錄加入,boost(boost的下載目錄),python/include(python的安裝目錄)

2、如果使用的是boost.python的靜態庫:在屬性->前置處理器->前置處理器定義添加BOOST_PYTHON_STATIC_LIB,否則編譯的為動態,會提示找不到python_boost*.lib什麼的

c++程式

// python_test.cpp : 定義控制台應用程式的進入點。//#include "stdafx.h"#include <iostream>#include <boost/python.hpp>using namespace std;using namespace boost::python;int _tmain(int argc, _TCHAR* argv[]){ Py_Initialize(); // 初始化 object main_module = import("__main__"); object main_namespace = main_module.attr("__dict__"); // 執行多個python語句:建立一個hello.txt文字檔 str Lines =  "hello = file(‘hello.txt‘, ‘w‘)\n"  "hello.write(‘Hello world first python!‘)\n"  "hello.close()"; exec(Lines, main_namespace); // 執行運算式 exec("result = 5 ** 2", main_namespace); // 提取並查看變數result的值 int five_squared = extract<int>(main_namespace["result"]); // 查看變數result的值 cout << "The five_squeared caculated by python is " << five_squared << endl; //載入sys module. object sys = import("sys"); // 提取python的版本資訊 std::string version = extract<std::string>(sys.attr("version")); std::cout << version << std::endl; //要求simple.py與可執行檔在相同路徑下! 運行ok str filename = "simple.py"; object simple = exec_file(filename, main_namespace, main_namespace); object foo = main_namespace["foo"]; int val = extract<int>(foo(5)); cout << "Python has caculated foo as " << val << endl; Py_Finalize(); cout << "My Python SUCCESS"<<endl ; system("pause"); return 0;} 

在目前的目錄下建立一個simple.py的Python檔案,內容如下:

def foo(i = 4):      return i**3  

(樣本程式源於網路)

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

c++調用python

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.