清洁方式将Python 3 Unicode转换为std :: string [英] Clean Way to Convert Python 3 Unicode to std::string

查看:1950
本文介绍了清洁方式将Python 3 Unicode转换为std :: string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Python 2 API封装了很多C ++(由于各种技术原因,我不能使用像swig或boost.python这样的东西)。当我必须传递一个字符串(通常是一个路径,总是ASCII)到C / C ++,我使用这样:

I wrap a lot of C++ using the Python 2 API (I can't use things like swig or boost.python for various technical reasons). When I have to pass a string (usually a path, always ASCII) into C/C++, I use something like this:

std::string file_name = PyString_AsString(py_file_name); 
if (PyErr_Occurred()) return NULL; 



现在我考虑更新到Python 3,其中 PyString _ * 方法不存在。我发现一个解决方案说我应该这样做:

PyObject* bytes = PyUnicode_AsUTF8String(py_file_name);
std::string file_name = PyBytes_AsString(bytes); 
if (PyErr_Occurred()) return NULL; 
Py_DECREF(bytes); 

但是这是两倍的行数,看起来有点丑内存泄漏,如果我忘了最后一行)。

However this is twice as many lines and seems a bit ugly (not to mention that it could introduce a memory leak if I forget the last line).

另一个选项是重新定义python函数来操作 bytes 对象, / p>

The other option is to redefine the python functions to operate on bytes objects, and to call them like this

def some_function(path_name):
    _some_function(path_name.encode('utf8'))

这不是可怕的,但它确实需要一个python边包装函数。

This isn't terrible, but it does require a python-side wrapper for each function.

有没有更清洁的方法来处理这个?

Is there some cleaner way to deal with this?

推荐答案

看起来像解决方案存在于python 3.3中, char * PyUnicode_AsUTF8(PyObject * unicode) 。这应该与来自python 2的 PyString_AsString()函数完全相同。

Looks like the solution exists in python 3.3, with char* PyUnicode_AsUTF8(PyObject* unicode). This should be exactly the same behavior as the PyString_AsString() function from python 2.

这篇关于清洁方式将Python 3 Unicode转换为std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆