Data encapsulation in C

后端 未结 5 1018
醉酒成梦
醉酒成梦 2020-12-24 10:05

I am currently working on an embedded system and I have a component on a board which appears two times. I would like to have one .c and one .h file for the component.

<
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-24 10:29

    I would like this data to be non-accessible from the "outside" of my component (only through special functions in my component).

    You can do it in this way (a big malloc including the data):

    #include 
    #include 
    #include 
    
    typedef struct {
        uint32_t pin_reset;
        uint32_t pin_drdy;
        uint32_t pin_start;
        volatile avr32_spi_t *spi_module;
        uint8_t cs_id;  
    } ads1248_options_t;
    
    void fn(ads1248_options_t *x)
    {
        int32_t *values = (int32_t *)(x + 1);
        /* values are not accesible via a member of the struct */
    
        values[0] = 10;
        printf("%d\n", values[0]);
    }
    
    int main(void)
    {
        ads1248_options_t *x = malloc(sizeof(*x) + (sizeof(int32_t) * 100));
    
        fn(x);
        free(x);
        return 0;
    }
    

提交回复
热议问题