c++ - 如何将 QString 复制到 wchar_t 缓冲区

标签 c++ qt

我使用的是旧 API,它需要指向文件名的字符数组的指针。

我想动态地命名,所以我使用这样的东西:

QString fileName = QString("./TestImage_%1_%2.bmp")
        .arg(static_cast<int>(position)).arg(imgCounter++);

然后每次需要保存文件时,我都会在堆上创建一个新数组:

wchar_t* array = new wchar_t[fileName.length() + 1];
fileName.toWCharArray(array);
array[fileName.length()] = 0;
ImageFileParams.pwchFileName = array; // API uses this to write the file
// ... rest of the code

我删除数组:

delete[] array;

这种内存的分配和删除在2019年有点搞笑...所以我这样声明了一个类成员buffer:

/** Buffer to hold dynamic names for use with IDS API*/
wchar_t mNameBuffer[256] = {'\0'};

现在的问题是,如何将动态 QString 的内容复制到此缓冲区并将指针传递给 API 调用?

最佳答案

如果你想变得现代,就变得现代:

std::wstring t = fileName.toStdWString();
ImageFileParams.pwchFileName = t.c_str();

无需猜测缓冲区大小。

关于c++ - 如何将 QString 复制到 wchar_t 缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57523012/

相关文章:

c++ - 如何在 Qt Creator 中设置 “set a breakpoint in malloc_error_break to debug”?

c++ - Qt 5.5.0 找不到 OpenGL 函数

c++ - 带有模型的 Qt TableView 包含指向自定义类的指针

c++ - 防止连接到插槽 ("Really"专用插槽)

c++ - #undef main 没有结果

c++ - 模板类继承

C++:用多个定界符拆分字符串并在结果中保留定界符?

c++ - 具有 const 参数的模板未按预期分派(dispatch)

java - Android:从 C++ 调用带有 byte[] 参数的 java 方法

android - 在不使用 qmake 的情况下在 Android 的 Qt 应用程序上使用自定义 AndroidManifest?