C 呼叫Python的API總結

2021-10-23 01:49:15 字數 3095 閱讀 6886

從pmodule模組裡load需要呼叫的函式並執行

c++向python傳遞引數

解析python的返回值pyobject* results

#include

py_initialize()

;…py_finalize()

;

所有的python程式都要在這之間執行

又分為以下兩種方式

pyobject *pname,

*pmodule;

pyrun_******string

("import sys");

//匯入系統模組

pyrun_******string()

;//指定pytest.py所在的目錄

pname =

pystring_fromstring

("pytest");

//指定要匯入的檔名

pmodule =

pyimport_import

(pname)

;//將pytest.py匯入模組指標pmodule

pyobject* pmodule;

pmodule =

pyimport_import

(pystring_fromstring

(「ptest」));

//將pytest匯入模組指標pmodule

又分為以下兩種方式

pyobject *pfunc,

*args,

*results;

pfunc=

pyobject_getattrstring

(pmodule,

"func");

//pmodule是上一步load好的python模組

args =

py_buildvalue

("(i)"

,12345);

//設定呼叫func時的輸入變數,這裡假設為12345

results=

pyobject_callobject

(pfunc, args)

;//執行func(12345),並將結果返回給results

pyobject *pclass,

*pdict,

*pinstance,

*class_args,

*results;

pdict =

pymodule_getdict

(pmodule)

;//拿到pmodule裡的所有類和函式定義

pclass=

pydict_getitemstring

(pdict,

"executor");

//找到名為executor的類

class_args =

py_buildvalue

("(s)"

,"./config.txt");

//設定類初始化需要的引數

pinstance=

pyinstance_new

(pclass, class_args,

null);

//初始化executor,建立例項pinstance

results=

pyobject_callmethod

(pinstance,

"func"

,"(i)"

,12345);

// 執行pinstance.func(12345)

因為在python中,所有的型別都經過了一層封裝,導致c++的引數需要做乙個型別轉換,轉換成pyobject才能傳入python。例如c++的乙個int就是個整數,該值占用8bytes(64位)的儲存空間,而乙個python的int其實是乙個pyobject 指向的24bytes的結構。前8bytes是個整數,代表引用次數,中間8bytes是個指向int型別定義的指標,最後8bytes才是這個int的值。所以c++和python之間引數的互相傳遞都需要呼叫python提供的api。

假設函式的輸入變數有三個分別為乙個整數(i),乙個浮點數(f)和乙個字串(s)

pyobject* args =

pytuple_new(3

);pyobject* arg1 =

py_buildvalue

("i"

,100);

// 整數引數

pyobject* arg2 =

py_buildvalue

("f"

,3.14);

// 浮點數引數

pyobject* arg3 =

py_buildvalue

("s"

,"hello");

// 字串引數

pytuple_setitem

(args,

0, arg1)

;pytuple_setitem

(args,

1, arg2)

;pytuple_setitem

(args,

2, arg3)

;

以上函式可簡化為

pyobject* args =

py_buildvalue

("(ifs)"

,100

,3.14

,"hello"

);

如果輸入引數是另乙個python函式的輸出結果pyobject* results (o)

pyobject* args =

py_buildvalue

("(o)"

, results)

;

具體引數格式parsing arguments and building values

同c++傳遞引數到python類似,呼叫解析函式

單個返回值:pyarg_parse()

多返回值:pyarg_parsetuple()

具體例子:1.7 format strings for pyarg_parsetuple()

C 呼叫 Python 的 API 解讀

官方 選擇你安裝的python版本 1.py buildvalue s yaoyin 等於 python中的 定義了乙個字串 yaoyin 2.pyobject pdict pydict new pydict setitemstring pdict,name py buildvalue s yaoy...

c 呼叫python的總結

最近因為專案的原因,經常使用python來編寫 深深的被python易學易用簡單快捷的方法所折服了,最近有些空閒,又研究一下原來做過的幾個程式,發現如果嵌入python的話 的編寫速度會高很多,之前只是看過內嵌lua的,對於python不是身為了解,所以此次那想利用c 內嵌python指令碼來實現功...

C 呼叫API介面

get post 請求兩種方式,我挑選了一種簡單的方式 關於c 呼叫api介面獲取到json資料的簡單方法 using var client newwebclient 如果只是獲取到json資料並沒多大用處 需要對其解析 轉json格式為c 類 json格式的各種操作 天氣api 下面以獲取天氣ap...