【问题标题】:returning a variable string in Py_BuildValue在 Py_BuildValue 中返回一个变量字符串
【发布时间】:2018-03-21 00:05:57
【问题描述】:

我正在用 C++ 编写以下测试用例:

using namespace boost::algorithm;
static PyObject* strtest(PyObject* self, PyObject* args)
{
    std::string s = "Boost C++ Libraries";
    to_upper(s);
    PyObject * python_val = Py_BuildValue("s", s);
    return python_val;
}

代码会编译和导入,但会产生看起来像是对内存位置的引用。

>>> math_demo.strtest()
' X\x0e'

我期待 'BOOST C++ LIBRARIES' 作为返回值

我错过了什么?

谢谢

【问题讨论】:

  • 你试过PyObject * python_val = Py_BuildValue("s", s.c_str()); 吗?
  • 优秀。这就是解决方案。如果您想发布作为答案,我会给予信任。

标签: python c++ boost


【解决方案1】:

[Python 3.Docs]: Parsing arguments and building values - PyObject* Py_BuildValue(const char *format, ...)(或任何其他 Python / C API 函数)适用于 C 类型而不是 C++ .

为了解决问题,请使用[cplusplus]: std::string::c_str

PyObject *python_val = Py_BuildValue("s", s.c_str());

【讨论】:

    猜你喜欢
    • 2020-06-19
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 2012-12-14
    • 2016-10-27
    相关资源
    最近更新 更多