PY_SSIZE_T_CLEAN macro的作用

PY_SSIZE_T_CLEAN macro的作用

Extending Python with C or C++中介紹了Python的C extension的寫法,它給出的範例前兩行如下:

#define PY_SSIZE_T_CLEAN
#include <Python.h>

其中#define PY_SSIZE_T_CLEAN的作用為何?簡單來說是讓用於解析extensions functions/methods參數的PyArg_ParseTuple函數把s#的長度參數當成Py_ssize_t而非int型別。

參考Parsing arguments and building values - Strings and buffersPyArg_ParseTuples#有兩個參數:

s# (str, read-only bytes-like object) [const char *, Py_ssize_t]

分別代表字串本身及其長度,其中長度的型別必須是Py_ssize_t

根據以下說明:

Note For all # variants of formats (s#, y#, etc.), the macro PY_SSIZE_T_CLEAN must be defined before including Python.h. On Python 3.9 and older, the type of the length argument is Py_ssize_t if the PY_SSIZE_T_CLEAN macro is defined, or int otherwise.

可以知道s#長度參數的型別預設是int,如果定義了PY_SSIZE_T_CLEAN,才會是Py_ssize_t型別。因此必須定義PY_SSIZE_T_CLEAN,否則會出現如SystemError: PY_SSIZE_T_CLEAN macro must be defined for ‘#’ formats的錯誤。

至於Py_ssize_t是什麼呢?參考Py_ssize_t

type Py_ssize_t
Part of the Stable ABI.
A signed integral type such that sizeof(Py_ssize_t) == sizeof(size_t). C99 doesn’t define such a thing directly (size_t is an unsigned integral type). See PEP 353 for details. PY_SSIZE_T_MAX is the largest positive value of type Py_ssize_t.

可知Py_ssize_t是一有號整數的型別,其長度等於size_t。而根據C size_tsize_t的大小不一定等於int,所以Python中才會有必須定義PY_SSIZE_T_CLEAN的規定。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值