我正在用 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;
}
Run Code Online (Sandbox Code Playgroud)
代码会编译并导入,但会生成看起来像是对内存位置的引用。
>>> math_demo.strtest()
' X\x0e'
Run Code Online (Sandbox Code Playgroud)
我期待'BOOST C++ LIBRARIES'作为返回值
我缺少什么?
谢谢
[Python.Docs]:解析参数和构建值 - 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());
Run Code Online (Sandbox Code Playgroud)