簡介

對於 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/,其中 prefixexec_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_NONEPyMODINIT_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 x has INT_MIN value 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_MAX corresponds 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 type is 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)

Cast value to type smaller from type larger, validating that no information was lost.

On release builds of Python, this is roughly equivalent to ((smaller) value) (in C++, static_cast<smaller>(value) will be used instead).

On debug builds (implying that Py_DEBUG is defined), this asserts that no information was lost with the cast from larger to smaller.

value, larger, and smaller may all be evaluated more than once in the expression; consequently, do not pass an expression with side-effects directly to this macro.

Py_BUILD_ASSERT(cond)

Asserts a compile-time condition cond, as a statement. The build will fail if the condition is false or cannot be evaluated at compile time.

Corresponds roughly to static_assert(cond) on C23 and above.

範例:

Py_BUILD_ASSERT(sizeof(PyTime_t) == sizeof(int64_t));

在 3.3 版被加入.

Py_BUILD_ASSERT_EXPR(cond)

Asserts a compile-time condition cond, as an expression that evaluates to 0. The build will fail if the condition is false or cannot be evaluated at compile time.

範例:

#define foo_to_char(foo) \
    ((char *)(foo) + Py_BUILD_ASSERT_EXPR(offsetof(struct foo, string) == 0))

在 3.3 版被加入.

Type size utilities

Py_ARRAY_LENGTH(array)

Compute the length of a statically allocated C array at compile time.

The array argument must be a C array with a size known at compile time. Passing an array with an unknown size, such as a heap-allocated array, will result in a compilation error on some compilers, or otherwise produce incorrect results.

這大致上相當於:

sizeof(array) / sizeof((array)[0])
Py_MEMBER_SIZE(type, member)

以位元組為單位回傳結構 (type) member 的大小。

Corresponds roughly to sizeof(((type *)NULL)->member).

在 3.6 版被加入.

Macro definition utilities

Py_FORCE_EXPANSION(X)

This is equivalent to X, which is useful for token-pasting in macros, as macro expansions in X are forcefully evaluated by the preprocessor.

Py_STRINGIFY(x)

x 轉換為 C 字串。例如 Py_STRINGIFY(123) 會回傳 "123"

在 3.4 版被加入.

Declaration utilities

The following macros can be used in declarations. They are most useful for defining the C API itself, and have limited use for extension authors. Most of them expand to compiler-specific spellings of common extensions to the C language.

Py_ALWAYS_INLINE

要求編譯器總是嵌入靜態行內函式 (static inline function),編譯器可以忽略它並決定不嵌入該函式。

Corresponds to always_inline attribute in GCC and __forceinline in MSVC.

在禁用函式嵌入的除錯模式下建置 Python 時,它可用於嵌入有性能要求的靜態行內函式。例如,MSC 在除錯模式下建置時禁用函式嵌入。

盲目地使用 Py_ALWAYS_INLINE 標記靜態行內函式可能會導致更差的性能(例如程式碼大小增加)。在成本/收益分析方面,編譯器通常比開發人員更聰明。

如果 Python 是在除錯模式下建置(如果 Py_DEBUG 巨集有被定義),Py_ALWAYS_INLINE 巨集就什麼都不會做。

它必須在函式回傳型別之前被指定。用法:

static inline Py_ALWAYS_INLINE int random(void) { return 4; }

在 3.11 版被加入.

Py_NO_INLINE

禁用函式的嵌入。例如,它減少了 C 堆疊的消耗:對大量嵌入程式碼的 LTO+PGO 建置很有用(請參閱 bpo-33720)。

Corresponds to the noinline attribute/specification on GCC and MSVC.

用法:

Py_NO_INLINE static int random(void) { return 4; }

在 3.11 版被加入.

Py_DEPRECATED(version)

Use this to declare APIs that were deprecated in a specific CPython version. The macro must be placed before the symbol name.

範例:

Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);

在 3.8 版的變更: 新增了 MSVC 支援。

Py_LOCAL(type)

Declare a function returning the specified type using a fast-calling qualifier for functions that are local to the current file. Semantically, this is equivalent to static type.

Py_LOCAL_INLINE(type)

Equivalent to