简体   繁体   English

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

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

I'm trying to share a struct similar to the following example: 我正在尝试共享类似于以下示例的结构:

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

I'm trying to share this struct between processes, the problem that I find is that when I initialize 'a' with malloc, I won't be able to access the array from within the second process. 我正在尝试在进程之间共享此结构,我发现的问题是,当我使用malloc初始化'a'时,将无法从第二个进程内访问该数组。 Is it possible to add this dynamic array to the memory mapped file? 是否可以将此动态数组添加到内存映射文件中?

You can have it as 你可以拥有它

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;

the trick is zero sized a array at the end of the structure and malloc larger then size of structure by actual size of a . 技巧是在结构的末尾a数组的大小设为零,然后malloc大于结构的大小乘以a的实际大小。

You can copy this structure to mmapped file. 您可以将此结构复制到映射文件。 You should copy sizeof(example)+val->asize bytes. 您应该复制sizeof(example)+val->asize个字节。 On the other side, just read asize and you know how many data you should read - so read sizeof(example) bytes, realloc and read additional asize bytes. 另一方面,只需读取asize知道应该读取多少数据-因此读取sizeof(example)字节,重新realloc并读取其他asize字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM