问题描述
我写了这段代码来改变python的工作目录到c++目录:
Py_Initialize();
// Get the c++ working directory
QString working_directory = QFileInfo(".").absolutePath();
qDebug() << "C++ wd: " << working_directory;
PyRun_SimpleString("import os");
// Import the os module
PyObject* pyOSModule = PyImport_ImportModule("os");
// Convert the std::string to c string
const char * wdCString = working_directory.toStdString().c_str();
// Create python working directory string
PyObject* pyWd = PyUnicode_FromString(wdCString);
// The chdir function of the os module
PyObject* pyChdirFunction = PyObject_GetAttrString(pyOSModule,(char*)"chdir");
// Call the chdir method with the working directory as argument
PyObject_CallFunction(pyChdirFunction,"s",pyWd);
PyRun_SimpleString("print('Python wd: ' + os.getcwd())");
输出为:
C++ wd: "Q:/Q/UVC Luftreinigungsanlage/System/Air Purification Management System"
OSError: [WinError 123] The filename,directory name,or volume label Syntax is incorrect: '\x01'
奇怪的是,使用普通的 python shell "Q:/Q/UVC Luftreinigungsanlage/System/Air Purification Management System" 是 os.chdir() 的有效字符串,这有效,但我认为这与所谓的没有区别使用 Python.h 库。
解决方法
wdCString
是一个悬空指针 - working_directory.toStdString()
是一个临时对象,其生命周期在下一行结束。
您可以延长其使用寿命,
const std::string& wd = working_directory.toStdString();
const char * wdCString = wd.c_str();
或者直接传递指针,
PyObject* pyWd = PyUnicode_FromString(working_directory.toStdString().c_str());