Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

C 與 Python 的雙向呼叫:從 C 呼叫 Python 到 C++ 嵌入 Python 模組

編輯:關於 Android 開發

C 與 Python 的雙向呼叫:從 C 呼叫 Python 到 C++ 嵌入 Python 模組

Python 累積了大量功能完善的开源庫,C/C++ 程式若想借用這些既有能力,最直接的方式就是在自己的程式中嵌入 Python 直譯器。這也是「膠水語言」這個稱呼的由來——Python 能輕易呼叫 C、C++,也能反過來被其他語言呼叫。

環境

  • Ubuntu 14.04
  • gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2
  • Python 2.7.6

一、C 呼叫 Python 的完整範例

先準備一個 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() 的格式字串

Py_BuildValue() 的作用與 PyArg_ParseTuple() 相反:前者把 C 資料結構轉成 Python 物件,函式原型為 PyObject *Py_BuildValue(char *format, ...)。它同樣辨識一系列格式字串,但傳入的參數只能是值,不能是指位器,回傳的是一個 Python 物件。

兩者還有一個關鍵差異:PyArg_ParseTuple() 的第一個參數必為元組;Py_BuildValue() 則不一定產生元組——只有當格式字串包含兩個以上格式單元時才會生成元組,格式字串為空時回傳 None。

以下說明中,括號內是回傳的 Python 物件類型,方括號內是傳入的 C 值類型:

  • "s" (string) [char *]:把 C 字串轉成 Python 物件;C 字串為空時回傳 None。
  • "s#" (string) [char *, int]:把 C 字串與其長度轉成 Python 物件。
  • "z" (string or None) [char *]:作用同 "s"。
  • "z#" (string or None) [char *, int]:作用同 "s#"。
  • "i" (integer) [int]:把 C 的 int 轉成 Python int。
  • "b" (integer) [char]:作用同 "i"。
  • "h" (integer) [short int]:作用同 "i"。
  • "l" (integer) [long int]:把 C 的 long 轉成 Python int。
  • "c" (string of length 1) [char]:把 C 的 char 轉成長度為 1 的 Python 字串。
  • "d" (float) [double]:把 C 的 double 轉成 Python 浮點數。
  • "f" (float) [float]:作用同 "d"。
  • "O&" (object) [converter, anything]:透過轉換函式把任意資料型別轉成 Python 物件,失敗時回傳 NULL。
  • "(items)" (tuple) [matching-items]:把一串 C 值轉成 Python 元組。
  • "[items]" (list) [matching-items]:把一串 C 值轉成 Python 串列。
  • "{items}" (dictionary) [matching-items]:把一串 C 值轉成 Python 字典,每兩個連續值組成一個鍵值對。

幾個實際對照:

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))

三、深入 C++ 呼叫 Python 模組

做過遊戲開發的人都知道,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 也是相當便利的選擇。兩者都採用同一套格式字串。

五、實務注意事項

  • 務必把 Python 的工作路徑切換到模組所在位置。
  • 載入時使用「模組名」而非「檔案名」,不要帶副檔名。
  • 模組載入與函式取得之後都要驗證是否成功(例如 PyCallable_Check),否則後續呼叫可能造成堆疊錯誤並使程式崩潰。
  • 用過的物件記得以 Py_DECREF(PyObject*) 解除引用,好讓 Python 的垃圾回收機制正常運作,避免記憶體持續累積。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved