編輯:關於 Android 開發
Python 累積了大量功能完善的开源庫,C/C++ 程式若想借用這些既有能力,最直接的方式就是在自己的程式中嵌入 Python 直譯器。這也是「膠水語言」這個稱呼的由來——Python 能輕易呼叫 C、C++,也能反過來被其他語言呼叫。
先準備一個 Python 檔 math_test.py:
def add_func(a, b):
return a + b
def sub_func(a, b):
return (a - b)
再寫 C 語言來源檔 c_call_python.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "python2.7/Python.h"
int main(int argc, char** argv)
{
int arg0 = 0, arg1 = 0;
if (argc == 3) {
arg0 = atoi(argv[1]);
arg1 = atoi(argv[2]);
} else {
printf("please input 2 args!!\n");
return -1;
}
Py_Initialize();
if (!Py_IsInitialized())
return -1;
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
PyObject *pModule;
PyObject *pFunction;
PyObject *pArgs;
PyObject *pRetValue;
pModule = PyImport_ImportModule("math_test");
if (!pModule) {
printf("import python failed!!\n");
return -1;
}
pFunction = PyObject_GetAttrString(pModule, "add_func");
if (!pFunction) {
printf("get python function failed!!!\n");
return -1;
}
pArgs = PyTuple_New(2);
PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", arg0));
PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", arg1));
pRetValue = PyObject_CallObject(pFunction, pArgs);
printf("%d + %d = %ld\n", arg0, arg1, PyInt_AsLong(pRetValue));
Py_DECREF(pModule);
Py_DECREF(pFunction);
Py_DECREF(pArgs);
Py_DECREF(pRetValue);
Py_Finalize();
return 0;
}
編譯與執行:
root@linux:~/code# gcc -o c_call_python c_call_python.c -lpython2.7 root@linux:~/code# ./c_call_python 12 15 12 + 15 = 27
整個流程可以概括為五步:Py_Initialize() 初始化直譯器 → PyImport_ImportModule() 載入模組 → PyObject_GetAttrString() 取得函式物件 → PyTuple_New/SetItem 組出參數元組 → PyObject_CallObject() 呼叫並取回結果。用完之後記得 Py_DECREF 釋放引用,最後呼叫 Py_Finalize() 收尾。
特別提醒:PyRun_SimpleString("sys.path.append('./')") 這一步不可省略。若沒有把模組所在路徑加入搜尋路徑,PyImport_ImportModule 會直接找不到檔案。
Py_BuildValue() 的作用與 PyArg_ParseTuple() 相反:前者把 C 資料結構轉成 Python 物件,函式原型為 PyObject *Py_BuildValue(char *format, ...)。它同樣辨識一系列格式字串,但傳入的參數只能是值,不能是指位器,回傳的是一個 Python 物件。
兩者還有一個關鍵差異:PyArg_ParseTuple() 的第一個參數必為元組;Py_BuildValue() 則不一定產生元組——只有當格式字串包含兩個以上格式單元時才會生成元組,格式字串為空時回傳 None。
以下說明中,括號內是回傳的 Python 物件類型,方括號內是傳入的 C 值類型:
幾個實際對照:
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}
Py_BuildValue("((ii)(ii)) (ii)", 1, 2, 3, 4, 5, 6)
-> (((1, 2), (3, 4)), (5, 6))
做過遊戲開發的人都知道,Lua 與 C++ 的搭配堪稱經典:把 Lua 腳本當成動態連結庫使用,兼得腳本開發的靈活性與原生程式的效能。Python 同樣能做到這件事。
在一個 C++ 應用中,若要實作一組介面一致的功能模組,一般做法是用動態連結庫當外掛。但如果外掛變動頻繁,改用 Python 腳本代替 DLL(可以把它想成「文字形式的動態連結庫」)會靈活得多:需求一變就改腳本,不必重新編譯連結二進位檔。
Python 提供了 C++ 函式庫,讓開發者能方便地從 C++ 程式中呼叫 Python 模組,官方文件可參考《Embedding Python in Another Application》。
步驟一:連結 Python 函式庫
Python 安裝目錄下已包含頭檔案(include 目錄)與函式庫檔案(Windows 下為 python27.lib),使用前需先完成連結。
步驟二:直接執行 Python 敘述
#include "python/Python.h"
int main() {
Py_Initialize(); // 初始化
PyRun_SimpleString("print 'hello'");
Py_Finalize(); // 釋放資源
}
步驟三:載入 Python 模組並呼叫函式
假設 ~/test 目錄下有 test.py:
def test_add(a, b):
print 'add ', a, ' and ', b
return a + b
則可用以下程式碼呼叫 test_add:
#include "python/Python.h"
#include <iostream>
using namespace std;
int main() {
Py_Initialize(); // 初始化
// 將 Python 工作路徑切換到待呼叫模組所在目錄,
// 一定要保證路徑名的正確性
string path = "~/test";
string chdir_cmd = string("sys.path.append(\"") + path + "\")";
const char* cstr_cmd = chdir_cmd.c_str();
PyRun_SimpleString("import sys");
PyRun_SimpleString(cstr_cmd);
// 載入模組
PyObject* moduleName = PyString_FromString("test"); // 模組名,不是檔案名
PyObject* pModule = PyImport_Import(moduleName);
if (!pModule) { // 載入模組失敗
cout << "[ERROR] Python get module failed." << endl;
return 0;
}
cout << "[INFO] Python get module succeed." << endl;
// 載入函式
PyObject* pv = PyObject_GetAttrString(pModule, "test_add");
if (!pv || !PyCallable_Check(pv)) { // 驗證是否載入成功
cout << "[ERROR] Can't find function (test_add)" << endl;
return 0;
}
cout << "[INFO] Get function (test_add) succeed." << endl;
// 設定參數
PyObject* args = PyTuple_New(2); // 2 個參數
PyObject* arg1 = PyInt_FromLong(4); // 參數一設為 4
PyObject* arg2 = PyInt_FromLong(3); // 參數二設為 3
PyTuple_SetItem(args, 0, arg1);
PyTuple_SetItem(args, 1, arg2);
// 呼叫函式
PyObject* pRet = PyObject_CallObject(pv, args);
// 獲取回傳值
if (pRet) { // 驗證是否呼叫成功
long result = PyInt_AsLong(pRet);
cout << "result:" << result;
}
Py_Finalize(); // 釋放資源
return 0;
}
C++ 向 Python 傳參
Python 的參數實際上就是元組,所以傳參的本質是構造一個合適的元組。常用寫法有兩種。
一是用 PyTuple_New 建立元組,再以 PyTuple_SetItem 逐一填入:
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);
二是直接用 Py_BuildValue 一次構造出整個元組:
PyObject* args = Py_BuildValue("ifs", 100, 3.14, "hello");
PyObject* args = Py_BuildValue("()"); // 無參數函式
其中 i、s、f 這類格式字串的含義同上表。
Python 回傳值轉為 C++
呼叫 Python 得到的都是 PyObject*,必須用函式庫提供的轉換函式取回實際數值,例如 PyInt_AsLong、PyFloat_AsDouble、PyString_AsString。若要一次解析多個回傳值,可用 PyArg_ParseTuple 把它當元組拆解;PyArg_Parse 也是相當便利的選擇。兩者都採用同一套格式字串。
Android 為空白包簽名:jarsigner 指令完整教學
Android 為空白包簽名:jarsigner 指令完整教學 前言:先前公司在騰訊開放平台認領應用時,遇到一個問題——需要為空白包簽名,再上傳審核。 騰訊開放平台的官方
EventBus 初探:源碼解析與核心原理詳解
緣由:平時工作因懶於動筆,技術與經驗缺乏積累,導致曾研究過的問題又忘記,於是決心從寫作開始,整理歸納工作中遇到的問題。 我們都知道,在 Android 中處理事件傳遞可用
Binder 中的 asInterface 到底做了什麼?源碼與實踐解析
Binder 中的 asInterface 到底做了什麼?源碼與實踐解析 使用 AIDL 進行跨進程通信時,工具會在 Stub 類中生成一個 asInterface 方法
Android 多選本地相冊:MediaStore 與縮圖優化
Android 多選本地相冊:MediaStore 與縮圖優化 許多社群或動態發布功能都需要圖片上傳。若系統相簿不支援多選,或無法滿足自訂互動需求,就可以自行實作一個本地