講述C++中調(diào)用Python腳本
作者:佚名 
  C++中調(diào)用Python腳本的意義就不講了,至少你可以把它當成文本形式的動態(tài)鏈接庫,為此我也苦惱很久,后來終于讓我找到了解決辦法。
 也許大家對與Python腳本還不是很了解,看完本文后對您一定會大有幫助,下文除了學習Python腳本的基本性質(zhì)外還對調(diào)用Python腳本時出現(xiàn)的問題進行全面研究。
需要的時候還可以改一改,只要不改變接口, C++的程序一旦編譯好了,再改就沒那么方便了 先看Python腳本代碼!
- #test function
 - def add(a,b):
 - print "in python function add"
 - print "a = " + str(a)
 - print "b = " + str(b)
 - print "ret = " + str(a+b)
 - return
 - def foo(a):
 - print "in python function foo"
 - print "a = " + str(a)
 - print "ret = " + str(a * a)
 - return
 
把上面的PPython腳本代碼存為pytest.py接下來是c++ 的代碼:
- #include "Python.h"
 - int main(int argc, char** argv)
 - {
 - // 初始化Python
 - //在使用Python系統(tǒng)前,必須使用Py_Initialize對其
 - //進行初始化。它會載入Python的內(nèi)建模塊并添加系統(tǒng)路
 - //徑到模塊搜索路徑中。這個函數(shù)沒有返回值,檢查系統(tǒng)
 - //是否初始化成功需要使用Py_IsInitialized。
 - Py_Initialize();
 - // 檢查初始化是否成功
 - if ( !Py_IsInitialized() )
 - {
 - return -1;
 - }
 - // 添加當前路徑
 - //把輸入的字符串作為Python代碼直接運行,返回0
 - //表示成功,-1表示有錯。大多時候錯誤都是因為字符串
 - //中有語法錯誤。
 - PyRun_SimpleString("import sys");
 - PyRun_SimpleString("sys.path.append('./')");
 - PyObject *pName,*pModule,*pDict,*pFunc,*pArgs;
 - // 載入名為pytest的腳本
 - pName = PyString_FromString("pytest");
 - pModule = PyImport_Import(pName);
 - if ( !pModule )
 - {
 - printf("can't find pytest.py");
 - getchar();
 - return -1;
 - }
 - pDict = PyModule_GetDict(pModule);
 - if ( !pDict )
 - {
 - return -1;
 - }
 - // 找出函數(shù)名為add的函數(shù)
 - pFunc = PyDict_GetItemString(pDict, "add");
 - if ( !pFunc || !PyCallable_Check(pFunc) )
 - {
 - printf("can't find function [add]");
 - getchar();
 - return -1;
 - }
 
編譯選項, 需要手動指定Python腳本的include 路徑, 和鏈接接路徑。
【編輯推薦】
責任編輯:chenqingxiang 
                    來源:
                    清華大學出版社
 














 
 
 
 
 
 
 