4

我需要在 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();
}

我想创建另一个函数,该函数采用 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")
{
    ...
}

我怀疑它与 PyUnicode_AsEncodedString 有关系,但是它返回一个 PyObject 所以我不知道如何把它放到我的缓冲区中......

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

4

1 回答 1

3

我怀疑它与 PyUnicode_AsEncodedString 有关系,但是它返回一个 PyObject 所以我不知道如何把它放到我的缓冲区中......

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

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

于 2009-02-20T19:26:50.703 回答