Chromium 中MemoryMappedFile使用例子c++

文件映射基础介绍参考微软官网:

使用文件映射 - Win32 apps | Microsoft Learn

在文件中创建视图 - Win32 apps | Microsoft Learn

创建命名的共享内存 - Win32 apps | Microsoft Learn

使用大页面创建文件映射 - Win32 apps | Microsoft Learn

从文件句柄获取文件名 - Win32 apps | Microsoft Learn

Chromium中在windows平台是对GetMappedFileName的封装实现:

本文主要介绍三种文件映射使用方法示例:

1、路径初始化mapfile

2、 文件句柄初始化mapfile

3、文件+偏移 初始化mapfile  【base::MemoryMappedFile::Region】

一、看下base::MemoryMappedFile定义:

base\files\memory_mapped_file.h

base\files\memory_mapped_file.cc

namespace base {class FilePath;class BASE_EXPORT MemoryMappedFile {public:enum Access {// Mapping a file into memory effectively allows for file I/O on any thread.// The accessing thread could be paused while data from the file is paged// into memory. Worse, a corrupted filesystem could cause a SEGV within the// program instead of just an I/O error.READ_ONLY,// This provides read/write access to a file and must be used with care of// the additional subtleties involved in doing so. Though the OS will do// the writing of data on its own time, too many dirty pages can cause// the OS to pause the thread while it writes them out. The pause can// be as much as 1s on some systems.READ_WRITE,// This provides read/write access to the mapped file contents as above, but// applies a copy-on-write policy such that no writes are carried through to// the underlying file.READ_WRITE_COPY,// This provides read/write access but with the ability to write beyond// the end of the existing file up to a maximum size specified as the// "region". Depending on the OS, the file may or may not be immediately// extended to the maximum size though it won't be loaded in RAM until// needed. Note, however, that the maximum size will still be reserved// in the process address space.READ_WRITE_EXTEND,#if BUILDFLAG(IS_WIN)// This provides read access, but as executable code used for prefetching// DLLs into RAM to avoid inefficient hard fault patterns such as during// process startup. The accessing thread could be paused while data from// the file is read into memory (if needed).READ_CODE_IMAGE,
#endif};// The default constructor sets all members to invalid/null values.MemoryMappedFile();MemoryMappedFile(const MemoryMappedFile&) = delete;MemoryMappedFile& operator=(const MemoryMappedFile&) = delete;~MemoryMappedFile();// Used to hold information about a region [offset + size] of a file.struct BASE_EXPORT Region {static const Region kWholeFile;friend bool operator==(const Region&, const Region&) = default;// Start of the region (measured in bytes from the beginning of the file).int64_t offset;// Length of the region in bytes.size_t size;};// Opens an existing file and maps it into memory. |access| can be read-only// or read/write but not read/write+extend. If this object already points// to a valid memory mapped file then this method will fail and return// false. If it cannot open the file, the file does not exist, or the// memory mapping fails, it will return false.[[nodiscard]] bool Initialize(const FilePath& file_name, Access access);[[nodiscard]] bool Initialize(const FilePath& file_name) {return Initialize(file_name, READ_ONLY);}// As above, but works with an already-opened file. |access| can be read-only// or read/write but not read/write+extend. MemoryMappedFile takes ownership// of |file| and closes it when done. |file| must have been opened with// permissions suitable for |access|. If the memory mapping fails, it will// return false.[[nodiscard]] bool Initialize(File file, Access access);[[nodiscard]] bool Initialize(File file) {return Initialize(std::move(file), READ_ONLY);}// As above, but works with a region of an already-opened file. |access|// must not be READ_CODE_IMAGE. If READ_WRITE_EXTEND is specified then// |region| provides the maximum size of the file. If the memory mapping// fails, it return false.[[nodiscard]] bool Initialize(File file, const Region& region, Access access);[[nodiscard]] bool Initialize(File file, const Region& region) {return Initialize(std::move(file), region, READ_ONLY);}const uint8_t* data() const { return data_; }uint8_t* data() { return data_; }size_t length() const { return length_; }span<const uint8_t> bytes() const { return make_span(data_, length_); }span<uint8_t> mutable_bytes() const { return make_span(data_, length_); }// Is file_ a valid file handle that points to an open, memory mapped file?bool IsValid() const;private:// Given the arbitrarily aligned memory region [start, size], returns the// boundaries of the region aligned to the granularity specified by the OS,// (a page on Linux, ~32k on Windows) as follows:// - |aligned_start| is page aligned and <= |start|.// - |aligned_size| is a multiple of the VM granularity and >= |size|.// - |offset| is the displacement of |start| w.r.t |aligned_start|.static void CalculateVMAlignedBoundaries(int64_t start,size_t size,int64_t* aligned_start,size_t* aligned_size,int32_t* offset);#if BUILDFLAG(IS_WIN)// Maps the executable file to memory, set |data_| to that memory address.// Return true on success.bool MapImageToMemory(Access access);
#endif// Map the file to memory, set data_ to that memory address. Return true on// success, false on any kind of failure. This is a helper for Initialize().bool MapFileRegionToMemory(const Region& region, Access access);// Closes all open handles.void CloseHandles();File file_;// `data_` is never allocated by PartitionAlloc, so there is no benefit to// using a raw_ptr.RAW_PTR_EXCLUSION uint8_t* data_ = nullptr;size_t length_ = 0;#if BUILDFLAG(IS_WIN)win::ScopedHandle file_mapping_;
#endif
};}  // namespace base#endif  // BASE_FILES_MEMORY_MAPPED_FILE_H_

二、例子演示:

1、demo\BUILD.gn

executable("04-mapfile") {sources = ["04-mapfile/client.cc",]if (is_win) {ldflags = [ "/LARGEADDRESSAWARE" ]}deps = ["//base","//build/win:default_exe_manifest",]
}

2、demo\04-mapfile\client.cc

#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <windows.h>
#include <iostream>#include "base/command_line.h"
#include "base/containers/span.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/memory_mapped_file.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "third_party/abseil-cpp/absl/types/optional.h"namespace {
base::FilePath GetTestFilePath() {return base::FilePath(FILE_PATH_LITERAL("d:/test.txt"));
}void initTest_1() {LOG(ERROR) << " initTest_1";// 以路径初始化mapfilebase::MemoryMappedFile map;bool is_ok = map.Initialize(GetTestFilePath());if (!is_ok) {LOG(ERROR) << "Initialize erro";return;}is_ok = map.IsValid();size_t lg = map.length();// base::span<uint8_t> bytes = map.mutable_bytes();std::string out(reinterpret_cast<const char*>(map.data()), lg);LOG(ERROR) << out;
}void initTest_2() {// 以文件句柄初始化mapfileLOG(ERROR) << " initTest_2";base::MemoryMappedFile map;base::File file(GetTestFilePath(),base::File::FLAG_OPEN | base::File::FLAG_READ);bool is_ok = map.Initialize(std::move(file));if (!is_ok) {LOG(ERROR) << "Initialize erro";return;}is_ok = map.IsValid();size_t lg = map.length();// base::span<uint8_t> bytes = map.mutable_bytes();std::string out(reinterpret_cast<const char*>(map.data()), lg);LOG(ERROR) << out;
}void initTest_3() {// 文件+偏移 初始化mapfileLOG(ERROR) << " initTest_3";base::MemoryMappedFile map;base::File file(GetTestFilePath(),base::File::FLAG_OPEN | base::File::FLAG_READ);int64_t nLength = file.GetLength();LOG(ERROR) << "File Length: " << nLength;// 0到40个字节区域base::MemoryMappedFile::Region region = {0, 40};bool is_ok = map.Initialize(std::move(file), region);if (!is_ok) {LOG(ERROR) << "Initialize erro";return;}is_ok = map.IsValid();size_t lg = map.length();LOG(ERROR) << "map.length(): " << lg; //40// base::span<uint8_t> bytes = map.mutable_bytes();std::string out(reinterpret_cast<const char*>(map.data()), lg);LOG(ERROR) << out;
}}  // namespaceint main(int argc, const char* argv[]) {base::CommandLine::Init(argc, argv);initTest_1();initTest_2();initTest_3();return 0;
}

3、gn gen out/debug

4、ninja -C out/debug demo:04-mapfile

5、编译运行之后效果:

6、test.txt文件内容如下:

#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <windows.h>
#include <iostream>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/470168.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

OpenHarmony4.1蓝牙芯片如何适配?触觉智能RK3568主板SBC3568演示

当打开蓝牙后没有反应时&#xff0c;需要排查蓝牙节点是否对应、固件是否加载成功&#xff0c;本文介绍开源鸿蒙OpenHarmony4.1系统下适配蓝牙的方法&#xff0c;触觉智能SBC3568主板演示 修改对应节点 开发板蓝牙硬件连接为UART1&#xff0c;修改对应的节点&#xff0c;路径为…

前端 JS面向对象 原型 prototype

目录 一、问题引出 二、prototype原型对象 三、小结 四、constructor 五、__proto__对象原型 六、原型链 一、问题引出 由于JS的构造函数存在内存浪费问题&#xff1a; function Star(name,age){this.namenamethis.ageagethis.singfunction () {console.log("唱歌&…

生成 Django 中文文档 PDF 版

文章目录 背景克隆 Django 文档和翻译仓库配置 conf.py设置和同步翻译生成 .pot 文件运行 sphinx-intl update复制翻译文件 构建 PDF生成 tex 文件安装 MikTeX生成 PDF Sphinx 生成文档 背景 浏览看到一个帖子&#xff0c;有个评论说可以用 sphinx 构建一个 pdf&#xff0c;正…

mysql 实现分库分表之 --- 基于 MyCAT 的分片策略详解

引言 在我们日常工作的项目中&#xff0c;特别是面向 C 端用户的产品&#xff0c;随着业务量的逐步扩大&#xff0c;数据量也呈指数级增长。为了应对日益增长的数据库压力&#xff0c;数据库优化已成为项目中不可或缺的一环&#xff0c;而分库分表则是海量数据优化方案中的重要…

JUC-locks锁

JUC-locks锁 1、JUC-locks锁概述2、管程模型3、ReentrantLock可重入锁3.1 ReentrantLock源码3.2 Sync静态内部类3.3 NonfairSync非公平锁3.4 FairSync公平锁 如有侵权&#xff0c;请联系&#xff5e; 如有错误&#xff0c;也欢迎批评指正&#xff5e; 1、JUC-locks锁概述 java…

GEE 数据集——美国gNATSGO(网格化国家土壤调查地理数据库)完整覆盖了美国所有地区和岛屿领土的最佳可用土壤信息

目录 简介 代码 引用 网址推荐 知识星球 机器学习 gNATSGO&#xff08;网格化国家土壤调查地理数据库&#xff09; 简介 gNATSGO&#xff08;网格化国家土壤调查地理数据库&#xff09;数据库是一个综合数据库&#xff0c;完整覆盖了美国所有地区和岛屿领土的最佳可用土…

kettle开发-Day43-数据对比

前言&#xff1a; 随着数字化的深入&#xff0c;各种系统及烟囱的建立&#xff0c;各系统之间的架构和数据存储方式不同&#xff0c;导致做数据仓库或数据湖时发现&#xff0c;因自建的系统或者非标准化的系统经常存在物理删除而不是软删除。这就延伸出一个问题&#xff0c;经常…

哪款开放式耳机好用?5款实力出众的开放式耳机按头安利!

随着耳机市场日益火爆&#xff0c;许多品牌与款式不断涌现。但是&#xff0c;不少劣质产品在核心性能上缺乏专业优化&#xff0c;且选用低质材料&#xff0c;在音质还原度和佩戴舒适性等关键方面存在明显短板&#xff0c;导致性能欠佳&#xff0c;聆听体验不佳&#xff0c;还可…

Unity资源打包Addressable资源保存在项目中

怎么打包先看“Unity资源打包Addressable AA包” 其中遗留一个问题&#xff0c;下载下来的资源被保存在C盘中了&#xff0c;可不可以保存在项目中呢&#xff1f;可以。 新建了一个项目&#xff0c;路径与“Unity资源打包Addressable AA包”都不相同了 1.创建资源缓存路径 在…

矩阵的各种计算:乘法、逆矩阵、转置、行列式等——基于Excel实现

在Excel中,可以使用内置的函数和公式来实现矩阵的各种计算。以下是具体方法: 矩阵乘法: 使用MMULT函数。如图矩阵A在单元格范围A1:B2,矩阵B在单元格范围D1:E2,结果矩阵的左上角单元格为G1:选中结果矩阵的区域(如G1:H2)。输入公式:=MMULT(A1:B2, D1:E2)。按Ctrl+Shift…

[ComfyUI]Flux:繁荣生态魔盒已开启,6款LORA已来,更有MJ6写实动漫风景艺术迪士尼全套

今天&#xff0c;我们将向您介绍一款非常实用的工具——[ComfyUI]Flux。这是一款基于Stable Diffusion的AI绘画工具&#xff0c;旨在为您提供一键式生成图像的便捷体验。无论您是AI绘画的新手还是专业人士&#xff0c;这个工具都能为您带来极大的便利。 在这个教程中&#xff…

【设计模式】关联关系与依赖关系

UML 图将事物之间的联系分为 6 种&#xff1a;关联、依赖、聚合、组合、泛化、实现 我认为关联关系和依赖关系非常不好理解。 我们看下定义&#xff1a; 关联&#xff1a;表示一种拥有的关系。具有方向性。如果一个类单方向的访问另一个类&#xff0c;称为单向关联。如果两个类…

前端Cypress自动化测试全网详解

Cypress 自动化测试详解&#xff1a;从安装到实战 Cypress 是一个强大的端到端&#xff08;End-to-End, E2E&#xff09;功能测试框架&#xff0c;基于 Node.js 构建&#xff0c;支持本地浏览器直接模拟测试&#xff0c;并具有测试录屏功能&#xff0c;极大地方便了测试失败时的…

#渗透测试#SRC漏洞挖掘#云技术基础02之容器与云

免责声明 本教程仅为合法的教学目的而准备&#xff0c;严禁用于任何形式的违法犯罪活动及其他商业行为&#xff0c;在使用本教程前&#xff0c;您应确保该行为符合当地的法律法规&#xff0c;继续阅读即表示您需自行承担所有操作的后果&#xff0c;如有异议&#xff0c;请立即停…

Android 下内联汇编,Android Studio 汇编开发

版权归作者所有&#xff0c;如有转发&#xff0c;请注明文章出处&#xff1a;https://cyrus-studio.github.io/blog/ 内联汇编 Android 内联汇编非常适用于 ARM 架构的性能优化和底层操作&#xff0c;通常用于加密、解密、特定指令优化等领域。 1. 基础语法 内联汇编在 C/C …

深入剖析【C++继承】:单一继承与多重继承的策略与实践,解锁代码复用和多态的编程精髓,迈向高级C++编程之旅

​​​​​​​ &#x1f31f;个人主页&#xff1a;落叶 &#x1f31f;当前专栏: C专栏 目录 继承的概念及定义 继承的概念 继承定义 定义格式 继承基类成员访问⽅式的变化 继承类模板 基类和派⽣类间的转换 继承中的作⽤域 隐藏规则 成员函数的隐藏 考察继承【作⽤…

RHCE的学习(16)(shell脚本编程)

第一章、shell入门基础 1.1 为什么学习和使用Shell编程 对于一个合格的系统管理员来说&#xff0c;学习和掌握Shell编程是非常重要的。通过编程&#xff0c;可以在很大程度上简化日常的维护工作&#xff0c;使得管理员从简单的重复劳动中解脱出来。 Shell程序的特点&#xff…

信号量和线程池

1.信号量 POSIX信号量&#xff0c;用与同步操作&#xff0c;达到无冲突的访问共享资源目的&#xff0c;POSIX信号量可以用于线程间同步 初始化信号量 #include <semaphore.h> int sem_init(sem_t *sem, int pshared, unsigned int value); sem&#xff1a;指向sem_t类…

docker运行ActiveMQ-Artemis

前言 artemis跟以前的ActiveMQ不是一个产品&#xff0c;原ActiveMQ改为ActiveMQ Classic, 现在的artemis是新开发的&#xff0c;和原来不兼容&#xff0c;全称&#xff1a;ActiveMQ Artemis 本位仅介绍单机简单部署使用&#xff0c;仅用于学习和本地测试使用 官网&#xff1a;…

区块链技术在电子政务中的应用

&#x1f493; 博客主页&#xff1a;瑕疵的CSDN主页 &#x1f4dd; Gitee主页&#xff1a;瑕疵的gitee主页 ⏩ 文章专栏&#xff1a;《热点资讯》 区块链技术在电子政务中的应用 区块链技术在电子政务中的应用 区块链技术在电子政务中的应用 引言 区块链技术概述 定义与原理 发…