Qt Linux 全局内存的文件映射

Qt Linux filemapping for global memory

所以我需要为 Linux 编写文件映射(Windows OpenFileMapping()MapViewOfFile() 等)。为此,我选择了 QSharedMemory。 但是我不确定如何让它与全局内存一起工作。

Linux 或 QSharedMemory 的功能是否有另一个正确的文件映射模拟?

QSharedMemory 更适合附加到 SysV 共享内存对象。听起来您正在寻找更多关于 memory-mapped 文件的 C++ 包装器(从您引用的函数的名称来看——我不知道任何 Windows API)。

我过去使用 boost::iostreams::mapped_file_source 取得过成功(对于文件的 read-only 映射):

// compiled, but not actually tested!

#include <boost/iostreams/device/mapped_file.hpp>

#include <QByteArray>
#include <QDebug>
#include <QString>

void useMappedFile(QString filename)
{
    boost::iostreams::mapped_file_source file(filename.toStdString());
    if (!file.is_open()) {
        qWarning() << "Failed to open file";
        return;
    }

    auto bytes = QByteArray::fromRawData(file.data(), file.size());

    someFunction(bytes);

    // do not allow 'file' to go out of scope before 'bytes', as it owns the
    // storage!  Read the description of 'QByteArray::fromRawData'.
}

同一命名空间中还有 mapped_file_sinkmapped_file,分别用于 write-only 和 read-write 映射。

QSharedMemory 用于在进程之间创建共享内存,而不是用于内存映射文件。 (参见Qt官方example)。

对于内存映射文件,您可以简单地在 QFile 上使用 .map() 函数,例如

QFile file("MyFile");
if (!file.open(QIODevice::ReadWrite)) {
     //handle error
}
uchar *memory = file.map(0, file.size());
if (memory) {
    //mapped ok, use memory here

    file.unmap();
} else {
   //handle error
}

.map()函数继承自QFileDevice。默认情况下,映射在其他进程之间共享,您可以使用 QFileDevice::MapPrivateOption 创建私有映射,其中对映射内存的更改不与其他进程(或磁盘文件)共享。