在以下情况下如何复制?

时间:2019-09-19 13:19:19

标签: c++ visual-c++ shared-memory memcpy

我有一个Memory mapped file和相应的MapViewOfFile手柄。 memory mapped file将包含两个部分的数据:

  1. unsigned int指定实际数据的长度
  2. 实际相关数据

例如如果我的实际数据长度为10个字符,则内存映射文件将类似于:

  

10
  abcdefghij

其中abcdefghij是我想要的数据,并且会有一个换行符b / w,其长度数字和数据。如果需要,我还可以自由使用任何其他定界符。

现在,我想首先读取unsigned int,以便能够读取实际数据。我正在考虑memcpy,但是我不确定如何获取确切的unsigned int值,因为我认为memcpy会逐字符复制。如何从内容中提取10

1 个答案:

答案 0 :(得分:1)

您可以这样做:

#include "windows.h"
#include <iostream>

int main() {
    const size_t buffer_size = 4098;
    const char* name = "my_shared_memory"; //sm name
    HANDLE file = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, buffer_size, name);
    LPVOID region = MapViewOfFile(file, FILE_MAP_ALL_ACCESS, 0, 0, buffer_size);

    const char* const msg = "this is my data"; //this is the string you want to pass
    const int msg_size = strlen(msg) + 1; //this is the size of the string data with \0
    const int total_size = msg_size + sizeof(int); //the total size of your data: the size of the string and the string by itself
    char* const data = (char*)malloc(total_size); //get some memory to place this data
    ((int*)data)[0] = msg_size; //set the first part of the data with the string msg size
    memcpy(data + sizeof(int), msg, msg_size); //set the msg by it self just after the size

    CopyMemory(region, data, total_size); //put on sm

    const int retrieved_size = ((int*)region)[0]; //retrieves the size of the msg from the sm
    char* const retrieved_msg = (char*)malloc(retrieved_size); //alloc some space for receive the msg with the retrieved size
    memcpy(retrieved_msg, (char*)region + sizeof(int), retrieved_size); //set the msg in the previous allocated memory
    std::cout << retrieved_msg << std::endl; //prints the msg

    free(data);
    free(retrieved_msg);
}

在此question中,您有一些解决方案来检查字节序。然后,如有必要,您可以再使用一个字节来存储此信息。如果字节序不同,则可以swap bytes


乔希评论的解决方案:

对于ASCII编码的大小,您可以将其保存为字符串,而不用将int二进制编码的大小存储在内存中:

const int max_digits_size = 3;
char number[max_digits_size + 1];
sprintf(number, "%d", msg_size);
//your total_size is now (max_digits_size + 1) + msg_size

//first you retrieve from sm the number as string in number_memcopied var, then you convert:
const int retrieved_size = strtol(number_memcopied, NULL, 10);