我编写了这个代码,将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 luftreiningsanlage/System/Air Purification Management System”是os.chdir()的有效字符串,它可以工作,但我认为在python.h库中调用它没有什么不同
wdCString
是一个悬空指针-working_directory.toStdString()
是一个临时对象,其生存期已在下一行结束你可以延长它的寿命
或者直接传递指针
相关问题 更多 >
编程相关推荐