或者更好的模板<T*>
?爲什麼mapped_file :: data返回char *而不是void *
如果內存映射文件中包含的32個整數的序列,如果data()
返回void*
,我們才能夠在靜態澆鑄到std::uint32_t
直接。
爲什麼助推作者選擇返回char*
?
編輯:正如指出的,如果可移植性是一個問題,需要翻譯。但是說一個文件(或者在這種情況下是一塊內存)是比字節流更多的比特流,IEEE754雙倍或者複雜的數據結構,在我看來這是一個非常廣泛的聲明,需要一些更多解釋。
即使具有與建議(和在這裏實現)會使代碼更具可讀性處理字節序,能夠直接映射到be_uint32_t
向量:
struct be_uint32_t {
std::uint32_t raw;
operator std::uint32_t() { return ntohl(raw); }
};
static_assert(sizeof(be_uint32_t)==4, "POD failed");
是否允許/建議投到be_uint32_t*
?爲什麼或者爲什麼不?
應該使用哪種類型的演員?
EDIT2:因爲它似乎很難得到的地步,而不是在討論天氣的elaborator的內存模型由位,字節或字我會重組給予一個例子:
#include <cstdint>
#include <memory>
#include <vector>
#include <iostream>
#include <boost/iostreams/device/mapped_file.hpp>
struct entry {
std::uint32_t a;
std::uint64_t b;
} __attribute__((packed)); /* compiler specific, but supported
in other ways by all major compilers */
static_assert(sizeof(entry) == 12, "entry: Struct size mismatch");
static_assert(offsetof(entry, a) == 0, "entry: Invalid offset for a");
static_assert(offsetof(entry, b) == 4, "entry: Invalid offset for b");
int main(void) {
boost::iostreams::mapped_file_source mmap("map");
assert(mmap.is_open());
const entry* data_begin = reinterpret_cast<const entry*>(mmap.data());
const entry* data_end = data_begin + mmap.size()/sizeof(entry);
for(const entry* ii=data_begin; ii!=data_end; ++ii)
std::cout << std::hex << ii->a << " " << ii->b << std::endl;
return 0;
}
鑑於map
文件包含正確順序的位,是否有其他理由避免使用reinterpret_cast來使用我的虛擬內存而不先複製它?
如果沒有,爲什麼強制用戶通過返回類型指針來執行reinterpret_cast?
請回答加分所有的問題:)
你可以使用'reinterpret_cast' ... – Brian
'void'不算什麼。解除引用無用。 Mmaps不是無用的 – sehe
@sehe:void僅僅意味着:「我不知道我指的是什麼,請確保在訪問數據之前進行操作!」。對我來說,比確定它指向字節更有意義,即使它確實指向小端32位整數! – baol