簡介¶
對於 Python 的應用程式開發介面使得 C 和 C++ 開發者能夠在各種層級存取 Python 直譯器。該 API 同樣可用於 C++,但為簡潔起見,通常將其稱為 Python/C API。使用 Python/C API 有兩個不同的原因,第一個是為特定目的來編寫擴充模組;這些是擴充 Python 直譯器的 C 模組,這可能是最常見的用法。第二個原因是在更大的應用程式中將 Python 作為零件使用;這種技術通常在應用程式中稱為 embedding(嵌入式)Python。
編寫擴充模組是一個相對容易理解的過程,其中「食譜 (cookbook)」方法很有效。有幾種工具可以在一定程度上自動化該過程,儘管人們從早期就將 Python 嵌入到其他應用程式中,但嵌入 Python 的過程並不像編寫擴充那樣簡單。
不論你是嵌入還是擴充 Python,許多 API 函式都是很有用的;此外,大多數嵌入 Python 的應用程式也需要提供自訂擴充模組,因此在嘗試將 Python 嵌入實際應用程式之前熟悉編寫擴充可能是個好主意。
語言版本相容性¶
Python 的 C API 與 C11 和 C++11 版本的 C 和 C++ 相容。
This is a lower limit: the C API does not require features from later C/C++ versions. You do not need to enable your compiler's "c11 mode".
編寫標準¶
如果你正在編寫要引入於 CPython 中的 C 程式碼,你必須遵循 PEP 7 中定義的指南和標準。無論你貢獻的 Python 版本如何,這些指南都適用。對於你自己的第三方擴充模組,則不必遵循這些約定,除非你希望最終將它們貢獻給 Python。
引入檔案 (include files)¶
使用 Python/C API 所需的所有函式、型別和巨集的定義都透過以下這幾行來在你的程式碼中引入:
#define PY_SSIZE_T_CLEAN
#include <Python.h>
這意味著會引入以下標準標頭:<stdio.h>、<string.h>、<errno.h>、<limits.h>、<assert.h> 和 <stdlib.h>(如果可用)。
備註
由於 Python 可能會定義一些會影響某些系統上標準標頭檔的預處理器 (pre-processor),因此你必須在引入任何標準標頭檔之前引入 Python.h。
建議在引入 Python.h 之前都要定義 PY_SSIZE_T_CLEAN。有關此巨集的說明,請參閱剖析引數與建置數值。
所有定義於 Python.h 中且使用者可見的名稱(另外透過標準標頭檔引入的除外)都具有 Py 或 _Py 前綴。以 _Py 開頭的名稱供 Python 實作內部使用,擴充編寫者不應使用。結構成員名稱沒有保留前綴。
備註
使用者程式碼不應定義任何以 Py 或 _Py 開頭的名稱。這會讓讀者感到困惑,並危及使用者程式碼在未來 Python 版本上的可移植性,這些版本可能會定義以這些前綴之一開頭的其他名稱。
標頭檔通常隨 Python 一起安裝。在 Unix 上它們位於目錄 prefix/include/pythonversion/ 和 exec_prefix/include/pythonversion/,其中 prefix 和 exec_prefix 由 Python 的 configure 腳本的相應參數定義,version 是 '%d.%d' % sys.version_info[:2]。在 Windows 上,標頭安裝在 prefix/include 中,其中 prefix 是指定給安裝程式 (installer) 用的安裝目錄。
要引入標頭,請將兩個(如果不同)目錄放在編譯器的引入搜尋路徑 (search path) 中。不要將父目錄放在搜尋路徑上,然後使用 #include <pythonX.Y/Python.h>;這會在多平台建置上壞掉,因為 prefix 下獨立於平台的標頭包括來自 exec_prefix 的平台特定標頭。
C++ 使用者應注意,儘管 API 完全使用 C 來定義,但標頭檔適當地將入口點聲明為 extern "C"。因此,無需執行任何特殊操作即可使用 C++ 中的 API。
有用的巨集¶
Python 標頭檔中定義了幾個有用的巨集,大多被定義在它們有用的地方附近(例如 Py_RETURN_NONE、PyMODINIT_FUNC),其他是更通用的工具程式。以下並不一定是完整的列表。
-
Py_CAN_START_THREADS¶
如果有定義此巨集,則目前系統就能夠啟動執行緒。
Currently, all systems supported by CPython (per PEP 11), with the exception of some WebAssembly platforms, support starting threads.
在 3.13 版被加入.
-
Py_GETENV(s)¶
類似於
getenv(s),但如果在命令列上傳遞了-E則回傳NULL(請見PyConfig.use_environment)。
文件字串巨集¶
-
PyDoc_STRVAR(name, str)¶
建立一個名為 name 的變數,可以在文件字串中使用。如果 Python 是在沒有文件字串的情況下建置 (
--without-doc-strings),則該值將為空字串。範例:
PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element."); static PyMethodDef deque_methods[] = { // ... {"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc}, // ... }
Expands to
PyDoc_VAR(name) = PyDoc_STR(str).
-
PyDoc_STR(str)¶
擴展至給定的輸入字串,或如果文件字串被禁用 (
--without-doc-strings) 則建立空字串。範例:
static PyMethodDef pysqlite_row_methods[] = { {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS, PyDoc_STR("Returns the keys of the row.")}, {NULL, NULL} };
-
PyDoc_VAR(name)¶
Declares a static character array variable with the given name. Expands to
static const char name[]範例:
PyDoc_VAR(python_doc) = PyDoc_STR( "A genus of constricting snakes in the Pythonidae family native " "to the tropics and subtropics of the Eastern Hemisphere.");
General utility macros¶
The following macros are for common tasks not specific to Python.
-
Py_UNUSED(arg)¶
將此用於函式定義中未使用的參數以消除編譯器警告。例如:
int func(int a, int Py_UNUSED(b)) { return a; }。在 3.4 版被加入.
-
Py_GCC_ATTRIBUTE(name)¶
Use a GCC attribute name, hiding it from compilers that don't support GCC attributes (such as MSVC).
This expands to
__attribute__((name))on a GCC compiler, and expands to nothing on compilers that don't support GCC attributes.
Numeric utilities¶
-
Py_ABS(x)¶
回傳
x的絕對值。The argument may be evaluated more than once. Consequently, do not pass an expression with side-effects directly to this macro.
If the result cannot be represented (for example, if
xhasINT_MINvalue for int type), the behavior is undefined.Corresponds roughly to
((x) < 0 ? -(x) : (x))在 3.3 版被加入.
-
Py_MAX(x, y)¶
-
Py_MIN(x, y)¶
Return the larger or smaller of the arguments, respectively.
Any arguments may be evaluated more than once. Consequently, do not pass an expression with side-effects directly to this macro.
Py_MAXcorresponds roughly to(((x) > (y)) ? (x) : (y)).在 3.3 版被加入.
-
Py_ARITHMETIC_RIGHT_SHIFT(type, integer, positions)¶
Similar to
integer >> positions, but forces sign extension, as the C standard does not define whether a right-shift of a signed integer will perform sign extension or a zero-fill.integer should be any signed integer type. positions is the number of positions to shift to the right.
Both integer and positions can be evaluated more than once; consequently, avoid directly passing a function call or some other operation with side-effects to this macro. Instead, store the result as a variable and then pass it.
type is unused and only kept for backwards compatibility. Historically, type was used to cast integer.
在 3.1 版的變更: This macro is now valid for all signed integer types, not just those for which
unsigned typeis legal. As a result, type is no longer used.
-
Py_CHARMASK(c)¶
引數必須是 [-128, 127] 或 [0, 255] 範圍內的字元或整數。這個巨集會將
c轉換為unsigned char並回傳。
Assertion utilities¶
-
Py_UNREACHABLE()¶
當你的設計中有無法達到的程式碼路徑時,請使用此選項。例如在
case語句已涵蓋了所有可能值的switch陳述式中的default:子句。在你可能想要呼叫assert(0)或abort()的地方使用它。在發布模式 (release mode) 下,巨集幫助編譯器最佳化程式碼,並避免有關無法存取程式碼的警告。例如該巨集是在發布模式下於 GCC 使用
__builtin_unreachable()來實作。In debug mode, and on unsupported compilers, the macro expands to a call to
Py_FatalError().Py_UNREACHABLE()的一個用途是,在對一個永不回傳但並未聲明為_Noreturn的函式之呼叫後使用。如果程式碼路徑是極不可能但在特殊情況下可以到達,則不得使用此巨集。例如在低記憶體條件下或系統呼叫回傳了超出預期範圍的值。在這種情況下,最好將錯誤回報給呼叫者。如果無法回報錯誤則可以使用
Py_FatalError()。在 3.7 版被加入.
- Py_SAFE_DOWNCAST(value, larger, smaller)