c++ - 使用 boost.python 从 UTF-8 编码的 char* 返回 python unicode 实例

标签 c++ python boost boost-python

我正在尝试做一些应该非常简单的事情,但我不太幸运地从现有文档中弄清楚如何做。

对于 python 2 项目,我试图将列表 gettext-translated 字符串作为 unicode 实例返回给 python。 gettext() 的返回值是 UTF-8 编码的 char*,使用 PyUnicode_FromString 将其转换为 python unicode 实例应该非常简单。我觉得这很容易做到,但我似乎不知道怎么做。

根据 Ignacio Vazquez-Abrams 和 Thomas K 的评论,我确实让这个对单个字符串有效;对于这种情况,您可以绕过所有 boost.python 基础设施。这是一个例子:

        PyObject* PyMyFunc() {
            const char* txt =  BaseClass::MyFunc();
            return PyUnicode_FromString(txt); 
    }       

用通常的 def 语句公开:

class_<MyCclass>("MyClass")
    .def("MyFunc", &MyClass::PyMyFunc);

不幸的是,当您想要返回 unicode 实例列表时,这不起作用。这是我天真的实现:

boost::python::list PyMyFunc() {
    std::vector<std::string> raw_strings = BaseClass::MyFunc();
    std::vector<std::string>::const_iterator i;
    boost::python::list result;

    for (i=raw_strings.begin(); i!=raw_strings.end(); i++)
        result.append(PyUnicode_FromString(i->c_str()));
    return result;
}

但这不会编译:boost::python::list 似乎确实可以处理 PyObject 值。

最佳答案

在 C++-SIG 邮件列表的帮助下,我现在可以正常工作了。需要两个额外的步骤:

  1. 使用 boost::python::handle<> 在 PyObject* 周围创建一个 C++ 包装器,它负责引用处理
  2. 使用 boost::python::object 在句柄周围创建一个 C++ 包装器,它允许将 PyObject* 实例用作(合理的)普通 C++ 类实例,因此 boost::python::list 可以处理。

有了这些知识,工作代码如下所示:

boost::python::list PyMyFunc() {
    std::vector<std::string> raw_strings = BaseClass::MyFunc();
    std::vector<std::string>::const_iterator i;
    boost::python::list result;

    for (i=raw_strings.begin(); i!=raw_strings.end(); i++)
        result.append(
             boost::python::object(
               boost::python::handle<>(
                 PyUnicode_FromString(i->c_str()))));
    return result;
}

关于c++ - 使用 boost.python 从 UTF-8 编码的 char* 返回 python unicode 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5064902/

相关文章:

python - 如何保存odoo的配置文件?

python - 获取 "No module named django_messages"

c++ - std::vector 的 boost::shared_ptr 的内存释放

c++ - Boost 图切割上的 3 个类(0、1、4)

c++ - 如何检查数组索引是否存在

c++ - (*this)[i] 在重载 [] 运算符之后?

c++ - 不能使用 `deflateInit`压缩修改后的数据

c++ - 在其定义中创建一个实例

python - 计算 Python3 中列表的相等元组元素

c++ - (如何)我可以为 Boost MultiIndex 近似 "dynamic"索引( key 提取器)吗?