2015-04-19 54 views
0

我試圖共享類似於以下示例的結構內動態數組:Ç視窗 - 內存映射文件 - 共享結構

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

我試圖進程之間共享這個結構,這個問題我發現當我用malloc初始化'a'時,我將無法從第二個進程中訪問數組。 是否有可能將此動態數組添加到內存映射文件中?

回答

0

你可以把它作爲

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實際尺寸。

您可以將此結構複製到mmapped文件。你應該複製sizeof(example)+val->asize字節。另一方面,只讀asize,你知道應該讀多少數據 - 所以請閱讀sizeof(example)字節,realloc並閱讀其他asize字節。