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

﹥>﹥吖頭↗ 提交于 2019-12-08 11:12:39

问题


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. Is it possible to add this dynamic array to the memory mapped file?


回答1:


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.

You can copy this structure to mmapped file. You should copy sizeof(example)+val->asize bytes. 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.



来源:https://stackoverflow.com/questions/29731266/c-windows-memory-mapped-file-dynamic-array-within-a-shared-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!