Write-Only pointer type

前端 未结 6 847
执念已碎
执念已碎 2021-01-30 16:14

I\'m writing software for an embedded system.

We are using pointers to access registers of an FPGA device.
Some of the registers are read-only, while others are wr

6条回答
  •  孤街浪徒
    2021-01-30 16:50

    In C, you can use pointers to incomplete types to prevent all dereferencing:


    /* writeonly.h */
    typedef struct writeonly *wo_ptr_t;
    

    /* writeonly.c */
    #include "writeonly.h"
    
    struct writeonly {
      int value 
    };
    
    /*...*/
    
       FOO_REGISTER->value = 42;
    

    /* someother.c */
    #include "writeonly.h"
    
    /*...*/
    
       int x = FOO_REGISTER->value; /* error: deref'ing pointer to incomplete type */
    

    Only writeonly.c, or in general any code that has a definition struct writeonly, can dereference the pointer. That code, of course, can accidentally read the value also, but at least all other code is prevented from dereferencing the pointers all together, while being able to pass those pointers around and store them in variables, arrays and structures.

    writeonly.[ch] could provide a function for writing a value.

提交回复
热议问题