C Windows – 内存映射文件 – 共享结构中的动态数组
我正在尝试共享类似于以下示例的结构:
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;
诀窍是结构末端的数组大小为零,而malloc
大于结构大小的实际大小。
您可以将此结构复制到mmapped文件。 您应该复制sizeof(example)+val->asize
字节。 另一方面,只需读取asize
并知道您应该读取多少数据 – 因此读取sizeof(example)
字节, realloc
和读取额外的asize
字节。