Search code examples
cstructauto-generate

Generate code for nested struct pointers in C


I have a bunch of nested structures with arrays of pointers-to inside. I need a tool to generate the (code) instances of the pointed-to data types.

typedef stuct
{
    TYPE_1  * data[5];
    int a;
}TOP_T;

typedef struct
{
    TYPE_2 * pToType1Array[2];
    char c;
}TYPE_1;

typedef struct
{
    int b;
}TYPE_2;

To properly use these two types, I need to create a total of 10 instances of TYPE_2 - because 5*2 - and 2 instances of TYPE_1 and then do assignment of the pointers to the instances.

TYPE_2 t2_0;
TYPE_2 t2_1;

TYPE_1 t1_0;
TYPE_1 t1_1;
TYPE_1 t1_2;
TYPE_1 t1_3;
TYPE_1 t1_4;

TOP_T first;

first.data[0] = &t1_0;
first.data[1] = &t1_1;
...

I know how to manually create the instances but would like a script/tool to do this.

I cannot use malloc.

I'm using Eclipse so I have access to the type-tree.

Now, I have to do this

/********* ST_CHRONO_TRACE_CONTEXT_T - one for each CHRONO_NUM_TRACE_CONTEXTS per CHRONO_NUM_SESSION_CONTEXTS session */
ST_CHRONO_TRACE_CONTEXT_T   CHRONO_TraceContext_0_0;
ST_CHRONO_TRACE_CONTEXT_T   CHRONO_TraceContext_0_1;
ST_CHRONO_TRACE_CONTEXT_T   CHRONO_TraceContext_1_0;
ST_CHRONO_TRACE_CONTEXT_T   CHRONO_TraceContext_1_1;
ST_CHRONO_TRACE_CONTEXT_T * CHRONO_TraceContext_PTRS[CHRONO_NUM_SESSION_CONTEXTS][CHRONO_NUM_TRACE_CONTEXTS] =
{
    {&CHRONO_TraceContext_0_0, &CHRONO_TraceContext_0_1},
    {&CHRONO_TraceContext_1_0, &CHRONO_TraceContext_1_1}
};

These definitions is what I want to auto-gen.


Solution

  • Since you cannot use malloc()-family functions, you must want either globals or stack-allocated locals. For the rather simple case you present, you could do it semi-automatically like so:

    TYPE_2 twos[10] = {0};
    TYPE_1 ones[5] = {{0}};
    TOP_T top = {{0}};
    
    static init_pointers() {
        int i, j;
        for (i = 0; i < 5; i += 1) {
            top.data[i] = ones + i;
            for (int j = 0; j < 2; j++) {
                ones[i].pToType1Array[j] = twos + (i * 2 + j);
            }
        }
    }
    
    /* ... */
    
        init_pointers();
    

    You can extend a function such as that to populate the non-pointer members algorithmically, too. If you really need to generate C source code programmatically, though, then you probably need to write your own tool to do so. Such a tool could use a similar approach (pointers to array elements) to produce code that does not rely on malloc(), either with or without a runtime initialization function such as I present.