Python c-api 和 unicode 字符串
我需要在 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,所以我不确定如何将其放入我的缓冲区中...
注意:上面的两种方法都是包装 python api 的 c++ Unicode 类的成员 我正在使用Python 3.0
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
返回的 PyObject 是一个 PyStringObject,所以您只需要使用
PyString_Size
和PyString_AsString
获取指向字符串缓冲区的指针并将其 memcpy 到您自己的缓冲区。如果您正在寻找一种直接从 PyUnicode 对象进入您自己的字符缓冲区的方法,我认为您无法做到这一点。
The PyObject returned is a PyStringObject, so you just need to use
PyString_Size
andPyString_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.