How to pass a union as a parameter to a function

phil05 picture phil05 · Apr 18, 2011 · Viewed 17.1k times · Source

This code is for a driver for a DAC chip.

I have a bitfield below which represents a 24-bit register. So what I need to do, is populate the bitfield and write it out over SPI to the chip.

    typedef struct {
        uint8_t rdwr_u8:       1;
        uint8_t not_used_u8:   3;
        uint8_t address_u8:    4;
        uint8_t reserved_u8:   8;
        uint8_t data_u8:       8;
        uint8_t padding_u8:    8;
    } GAIN_REG_st;

In my initialisation function I create a union as below.

    union{
        GAIN_REG_st GAIN_st;
        uint32_t G_32;
    } G_u;

Now I need to pass a GAIN_REG_st bitfield to a function which will populate it.

Once it's populated I can assign the bitfield to a 32-bit integer and pass that integer to a low level function to write over SPI.

How do I pass the bitfield GAIN_REG_st to a function when it's inside a union? (Can you show a function prototype and call)?

How does the function access the bitfield's members? (would it be like G_u.GAIN_st.rdwr_u8 = 1?)

Answer

user82238 picture user82238 · Apr 18, 2011
union G_u
  the_union;

the_union.GAIN_st.address_u8 = 0x4;

function_call( &the_union );

void function_call( union G_u *the_union )
{
    uint8
        address;

    address = the_union->GAIN_st.address_u8;

    return;
}

Do you mean this? it's a union, so why pass an internal member? it won't make any difference. They all start at the same memory offset.