【问题标题】:Extract a python str with C API, compatible with python 2&3使用 C API 提取 python str,兼容 python 2&3
【发布时间】:2016-11-30 09:58:48
【问题描述】:

我的 c++ 代码运行 python 解释器来读取外部 python 文件,我正在尝试让 C API 接受 python 2 和 python 3 字符串。

如果是python 2.7.11,我使用PyString_CheckPyString_AsString

如果是python 3.5.2,我使用PyUnicode_CheckPyUnicode_AsUTF8String

前一种技术在 python 3.x 中已弃用。

我希望后者兼容这两个版本。但是,PyUnicode_Check 在 python 2 下为 str 类型的参数返回 false。此外,PyUnicode_AsUTF8String 在这种情况下会出现分段错误。

我做错了什么?

【问题讨论】:

    标签: string python-3.x python-2.x python-c-api python-unicode


    【解决方案1】:

    我终于找到了一种从 python 2.7 和 3.5 版本(至少)中提取字符串的方法

    PyObject *s;
    if( PyUnicode_Check(py_val) ) {  // python3 has unicode, but we convert to bytes
        s = PyUnicode_AsUTF8String(py_val);
    } else if( PyBytes_Check(py_val) ) {  // python2 has bytes already
        s = PyObject_Bytes(py_val);
    } else {
        // Not a string => Error, warning ...
    }
    
    // If succesfully converted to bytes, then convert to C++ string
    std::string val("");
    if(s) {
        val = std::string( PyBytes_AsString(s) );
        Py_XDECREF(s);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      相关资源
      最近更新 更多