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