C++調(diào)用Python基礎(chǔ)功能實(shí)例詳解
c++調(diào)用Python首先安裝Python,以win7為例,Python路徑為:c:\Python35\,通過mingw編譯c++代碼。
編寫makefile文件,首先要添加包含路徑:
inc_path += c:/Python35/include
然后添加鏈接參數(shù):
ld_flag += c:/Python35/libs/libpython35.a
在源文件中添加頭文件引用:
#include "Python.h"
Python解釋器需要進(jìn)行初始化,完成任務(wù)后需要終止:
void start()
{
  int r=Py_IsInitialized(); //1為已經(jīng)初始化了
  if (r==0)
  {
    //Py_SetPythonHome(L"C:\\Python35");
    Py_Initialize(); //初始化
    p_main_Module =PyImport_ImportModule("__main__");
    if (!p_main_Module)
    {
      throw "";
    }
  }
}
void end()
{
  Py_Finalize(); //清理
}
程序部署時(shí)可以將c:\Python35\lib目錄復(fù)制到執(zhí)行程序路徑下,或者通過Py_SetPythonHome(L"C:\\Python35");設(shè)置Python的安裝目錄。
C++調(diào)用Python的基本需求:
1、運(yùn)行Python指令
PyRun_SimpleString("print(os.getcwd(),a)");
pyext.eval(R"(a+='qwer')");
2、加載Python模塊
PyObject * pModule =PyImport_ImportModule("tp"); //test:Python文件名,若腳本有錯(cuò)則返回空
PyRun_SimpleString("import os");
3、給Python的變量賦值
對(duì)于數(shù)值,使用Py_BuildValue:
Py_BuildValue("") None
Py_BuildValue("i", 123) 123
Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)
Py_BuildValue("s", "hello") 'hello'
Py_BuildValue("ss", "hello", "world") ('hello', 'world')
Py_BuildValue("s#", "hello", 4) 'hell'
Py_BuildValue("()") ()
Py_BuildValue("(i)", 123) (123,)  
Py_BuildValue("(ii)", 123, 456) (123, 456)
Py_BuildValue("(i,i)", 123, 456) (123, 456)
Py_BuildValue("[i,i]", 123, 456) [123, 456]
Py_BuildValue("{s:i,s:i}", "abc", 123, "def", 456) {'abc': 123, 'def': 456}
對(duì)于其他數(shù)據(jù)結(jié)構(gòu),使用相應(yīng)的函數(shù)設(shè)置,例如:
PyObject *pArgs = PyTuple_New(1);
PyObject *pDict = PyDict_New();  //創(chuàng)建字典類型變量 
PyDict_SetItemString(pDict, "Name", Py_BuildValue("s", "WangYao")); //往字典類型變量中填充數(shù)據(jù) 
PyDict_SetItemString(pDict, "Age", Py_BuildValue("i", 25)); //往字典類型變量中填充數(shù)據(jù) 
PyTuple_SetItem(pArgs, 0, pDict);//0---序號(hào) 將字典類型變量添加到參數(shù)元組中 
構(gòu)造好對(duì)象以后,通過PyObject_SetAttrString來設(shè)置進(jìn)入Python中:
PyObject *ps=PyUnicode_DecodeUTF8(val,strlen(val),"ignore"); //構(gòu)造了一個(gè)對(duì)象 PyObject_SetAttrString(p_main_Module,key,ps); //設(shè)置
4、獲取Python變量的值
首先取得變量的指針,然后通過PyArg_Parse解析
pModule =PyImport_ImportModule("__main__");
pReturn = PyObject_GetAttrString(pModule, "a"); //可以獲得全局變量
int size = PyDict_Size(pReturn); 
PyObject *pNewAge = PyDict_GetItemString(pReturn, "Age"); 
int newAge;
PyArg_Parse(pNewAge, "i", &newAge); 
對(duì)于元組的解析:
int ok;
ok = PyArg_ParseTuple(args, "s", &s); //Python call: f('whoops!')
ok = PyArg_ParseTuple(args, "lls", &k, &l, &s);//Python call: f(1, 2,'three')
ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);//Python call: f((1, 2), 'three')
ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);//Python calls:
//f('spam')
//f('spam', 'w')
//f('spam', 'wb', 100000)
5、調(diào)用Python函數(shù)
PyObject * pfun=PyObject_GetAttrString(pModule, "testdict"); //testdict:Python文件中的函數(shù)名 PyObject *pReturn = PyEval_CallObject(pfun, pArgs); //調(diào)用函數(shù)
6、設(shè)置函數(shù)讓Python調(diào)用
首先定義c函數(shù),然后聲明方法列表,然后聲明模塊,然后增加這個(gè)模塊,最后調(diào)用
static int numargs=1890;
static PyObject* emb_numargs(PyObject *self, PyObject *args) //C函數(shù)
{
  if(!PyArg_ParseTuple(args, ":numargs"))
    return NULL;
  return PyLong_FromLong(numargs);
}
static PyMethodDef EmbMethods[] = { //方法列表
  {"numargs", emb_numargs, METH_VARARGS,
   "Return the number of arguments received by the process."},
  {NULL, NULL, 0, NULL}
};
static PyModuleDef EmbModule = { //模塊聲明
  PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods,
  NULL, NULL, NULL, NULL
};
static PyObject* PyInit_emb(void) //模塊初始化函數(shù)
{
  return PyModule_Create(&EmbModule);
}
//增加模塊:
PyImport_AppendInittab("emb", &PyInit_emb); //增加一個(gè)模塊
Python部分代碼:
import emb
print("Number of arguments", emb.numargs())
以上所述是小編給大家介紹的C++調(diào)用Python基礎(chǔ)功能實(shí)例詳解,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)我們網(wǎng)站的支持!
欄 目:C語言
下一篇:C++ 中使用lambda代替 unique_ptr 的Deleter的方法
本文標(biāo)題:C++調(diào)用Python基礎(chǔ)功能實(shí)例詳解
本文地址:http://www.jygsgssxh.com/a1/Cyuyan/1627.html
您可能感興趣的文章
- 04-02c語言函數(shù)調(diào)用后清空內(nèi)存 c語言調(diào)用函數(shù)刪除字符
 - 04-02c語言沒有round函數(shù) round c語言
 - 04-02c語言調(diào)用函數(shù)求fibo C語言調(diào)用函數(shù)求階乘
 - 01-10深入理解C++中常見的關(guān)鍵字含義
 - 01-10使用C++實(shí)現(xiàn)全排列算法的方法詳解
 - 01-10APUE筆記之:進(jìn)程環(huán)境詳解
 - 01-10c++中inline的用法分析
 - 01-10用C++實(shí)現(xiàn)DBSCAN聚類算法
 - 01-10全排列算法的非遞歸實(shí)現(xiàn)與遞歸實(shí)現(xiàn)的方法(C++)
 - 01-10C++大數(shù)模板(推薦)
 


閱讀排行
- 1C語言 while語句的用法詳解
 - 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹的示例代碼(圣誕
 - 3利用C語言實(shí)現(xiàn)“百馬百擔(dān)”問題方法
 - 4C語言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
 - 5c語言計(jì)算三角形面積代碼
 - 6什么是 WSH(腳本宿主)的詳細(xì)解釋
 - 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
 - 8正則表達(dá)式匹配各種特殊字符
 - 9C語言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
 - 10C語言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
 
本欄相關(guān)
- 04-02c語言函數(shù)調(diào)用后清空內(nèi)存 c語言調(diào)用
 - 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
 - 04-02c語言的正則匹配函數(shù) c語言正則表達(dá)
 - 04-02c語言用函數(shù)寫分段 用c語言表示分段
 - 04-02c語言中對(duì)數(shù)函數(shù)的表達(dá)式 c語言中對(duì)
 - 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排
 - 04-02c語言沒有round函數(shù) round c語言
 - 04-02c語言分段函數(shù)怎么求 用c語言求分段
 - 04-02C語言中怎么打出三角函數(shù) c語言中怎
 - 04-02c語言調(diào)用函數(shù)求fibo C語言調(diào)用函數(shù)求
 
隨機(jī)閱讀
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
 - 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
 - 01-10C#中split用法實(shí)例總結(jié)
 - 01-11ajax實(shí)現(xiàn)頁面的局部加載
 - 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
 - 01-10delphi制作wav文件的方法
 - 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
 - 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
 - 04-02jquery與jsp,用jquery
 - 01-10使用C語言求解撲克牌的順子及n個(gè)骰子
 


