c++ 返回Py_BuildValue中的变量字符串

7cwmlq89  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(71)

下面是一个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'作为返回值
我错过了什么?
谢谢

yqlxgs2m

yqlxgs2m1#

【巨蟒.蟒】:解析参数和构建值- PyObject *Py_BuildValue(const char *format,.)(或任何其他 Python / C API 函数)适用于 C(不是 C++)类型
要解决这个问题,请使用[CPPReference]: std::basic_string<CharT,Traits,Allocator>::c_str

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

字符串

相关问题