简体   繁体   中英

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. 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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