如何使用 Python 的 C API 避免在 Python 3.3 中弃用的函数将 unicode 字符串转换为大写/小写/标题大小写?

问题描述

中所述

https://docs.python.org/3/c-api/unicode.html#unicode-character-properties,

Py_UNICODE_toupper 和朋友自 Python 3.3 起已弃用,当时实施 PEP 393。但是,似乎没有任何替代品。特别是,C API 似乎不允许调用诸如 'abc'.upper() 之类的方法的底层 C 函数

这是否意味着 C API 从 Python 3.3 开始不再支持这些基本的 str 转换?有什么解决办法吗?

解决方法

您可以调用这些方法。请参阅Call Protocol

示例:

test.c

#include <Python.h>

__declspec(dllexport)
PyObject* upper(PyObject* arg) {
    return PyObject_CallMethod(arg,"upper",NULL);
}

使用 ctypes 的演示:

>>> from ctypes import *
>>> dll = PyDLL('./test')
>>> dll.upper.argtypes = py_object,>>> dll.upper.restype = py_object
>>> dll.upper('hello')
'HELLO'