【问题标题】:How to get real string from python c-api to python script?如何从 python c-api 获取真正的字符串到 python 脚本?
【发布时间】:2018-10-25 19:39:51
【问题描述】:

我尝试使用以下方法将字符串从 c++ 发送到 python 字符串:

PyObject* pyString = PyUnicode_FromString("/abc/def.html/a%22.php?abc=&def=%22;%00s%01");
....
PyObject* pyArgs = Py_BuildValue("(z)", pyString);
...
PyObject_CallObject(pFunc, pyArgs);

但在脚本中字符串不好:

function(data):
    print(data)

结果是:

/abc/def.html/a              bogus %pp?abc=&def=                    %;(null)%

发生了什么事?,如果我尝试使用 %% 转义 % 字符可以正常工作,但 PyUnicode_FromString 不是 printf 格式。

这是 PyUnicode_FromString 函数的错误吗?,我需要原生 python 转义吗?还是需要手动转义?

【问题讨论】:

    标签: c++ python-3.x c++11 python-c-api


    【解决方案1】:
    PyObject* pyArgs = Py_BuildValue("(z)", pyString);
    

    这条线是错误的。 'z'Py_BuildValue 中告诉它您传递的参数是 const char* 并且 Python 会将其转换为 Python 字符串。但是,您传递的参数已经是 Python 字符串。因此,它会尝试将PyObject* 重新解释为const char*,从而产生垃圾。

    正确的解决办法是

    PyObject* pyArgs = Py_BuildValue("(O)", pyString);
    

    它只是将pyString 解释为一个 Python 对象(就是这样!),或者

    PyObject* pyArgs = Py_BuildValue("(z)", "/abc/def.html/a%22.php?abc=&def=%22;%00s%01");
    

    跳过自己创建pyString

    【讨论】:

      猜你喜欢
      • 2020-10-12
      • 2010-11-03
      • 2011-07-06
      • 2017-08-06
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 2020-08-03
      • 2019-08-06
      相关资源
      最近更新 更多