C Windows-内存映射文件-共享结构中的动态数组 [英] 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
字节.
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.
这篇关于C Windows-内存映射文件-共享结构中的动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!