views:

352

answers:

1

I need to convert between python objects and c strings of various encodings. Going from a c string to a unicode object was fairly simple using PyUnicode_Decode, however Im not sure how to go the other way

//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();
}

I want to create another function that takes the python Unicode string and puts it in a buffer using a given encodeing, eg:

//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")
{
    ...
}

I suspect it has somthing to do with PyUnicode_AsEncodedString however that returns a PyObject so I'm not sure how to put that into my buffer...

Note: both methods above are members of a c++ Unicode class that wraps the python api I'm using Python 3.0

+1  A: 

I suspect it has somthing to do with PyUnicode_AsEncodedString however that returns a PyObject so I'm not sure how to put that into my buffer...

The PyObject returned is a PyStringObject, so you just need to use PyString_Size and PyString_AsString to get a pointer to the string's buffer and memcpy it to your own buffer.

If you're looking for a way to go directly from a PyUnicode object into your own char buffer, I don't think that you can do that.

Miles