Python c-api 和 unicode 字符串

Fir*_*cer 5 c python python-c-api

我需要在 python 对象和各种编码的 c 字符串之间进行转换。使用 PyUnicode_Decode 从 ac 字符串到 unicode 对象相当简单,但是我不知道如何走另一条路

//char* can be a wchar_t or any other element size, just make sure it is correctly terminated for its encoding
Unicode(const char *str, size_t bytes, const char *encoding="utf-16", const char *errors="strict")
    :Object(PyUnicode_Decode(str, bytes, encoding, errors))
{
    //check for any python exceptions
    ExceptionCheck();
}
Run Code Online (Sandbox Code Playgroud)

我想创建另一个函数,它接受 python Unicode 字符串并使用给定的编码将其放入缓冲区中,例如:

//fills buffer with a null terminated string in encoding
void AsCString(char *buffer, size_t bufferBytes,
    const char *encoding="utf-16", const char *errors="strict")
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

我怀疑它与 PyUnicode_AsEncodedString 有关,但是它返回一个 PyObject,所以我不确定如何将其放入我的缓冲区中......

注意:上面的两种方法都是包装 python api 的 c++ Unicode 类的成员,我正在使用 Python 3.0

Mil*_*les 4

我怀疑它与 PyUnicode_AsEncodedString 有关,但是它返回一个 PyObject,所以我不确定如何将其放入我的缓冲区中......

返回的 PyObject 是一个 PyStringObject,因此您只需使用PyString_SizePyString_AsString获取指向字符串缓冲区的指针,并将其 memcpy 到您自己的缓冲区。

如果您正在寻找一种直接从 PyUnicode 对象进入您自己的字符缓冲区的方法,我认为您无法做到这一点。