在调用C++时,会出现错误

2024-10-02 20:38:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了这个代码,将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库中调用它没有什么不同


Tags: the目录stringospyrunsystemdirectoryworking
1条回答
网友
1楼 · 发布于 2024-10-02 20:38:49

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());

相关问题 更多 >