Python c-api和unicode字符串

Python c-api和unicode字符串,python,c,python-c-api,Python,C,Python C Api,我需要在python对象和各种编码的c字符串之间进行转换。使用PyUnicode_解码从c字符串转换为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="ut

我需要在python对象和各种编码的c字符串之间进行转换。使用PyUnicode_解码从c字符串转换为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_asencodeString有关,但是它返回一个PyObject,所以我不确定如何将其放入缓冲区

注意:上面的两个方法都是一个C++ Puxode类的成员,它封装了Python API 我正在使用Python 3.0

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

返回的PyObject是一个PyStringObject,因此您只需要使用
PyString\u Size
PyString\u AsString
来获取指向字符串缓冲区的指针,并将其存储到您自己的缓冲区

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