C Windows - 内存映射文件 - 共享结构中的动态数组

C Windows - Memory Mapped File - dynamic array within a shared struct

我正在尝试共享类似于以下示例的结构:

typedef struct { 
    int *a; 
    int b; 
    int c;
} example;

我试图在进程之间共享这个结构,我发现的问题是当我用 malloc 初始化 'a' 时,我将无法从第二个进程中访问数组。 是否可以将此动态数组添加到内存映射文件中?

你可以把它当作

typedef struct { 
    int b; 
    int c;
    int asize; // size of "a" in bytes - not a number of elements
    int a[0];
} example;

/* allocation of variable */
#define ASIZE   (10*sizeof(int))
example * val = (example*)malloc(sizeof(example) + ASIZE);
val->asize = ASIZE;

/* accessing "a" elements */
val->a[9] = 125;

诀窍是结构末尾的零大小 a 数组和 malloc 比结构大小大 a 的实际大小。

您可以将此结构复制到映射文件。您应该复制 sizeof(example)+val->asize 个字节。另一方面,只需阅读 asize,您就知道应该阅读多少数据 - 所以阅读 sizeof(example) 字节,realloc 并阅读额外的 asize 字节。