Write-Only pointer type

前端 未结 6 943
执念已碎
执念已碎 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:43

    I would use a combination of structs to rappresent the register and a pair of functions to handle them.

    In a fpga_register.h you would have something like

    #define FPGA_READ = 1; 
    #define FPGA_WRITE = 2;
    typedef struct register_t {
        char permissions;
    } FPGARegister;
    
    FPGARegister* fpga_init(void* address, char permissions);
    
    int fpga_write(FPGARegister* register, void* value);
    
    int fpga_read(FPGARegister* register, void* value);
    

    with READ and WRITE in xor to express permissions.

    Than in the fpga_register.c you would define a new struct

    typedef struct register_t2 {
        char permissions;
        void * address;
    } FPGARegisterReal;
    

    so that you returns a pointer to it instead of a pointer to FPGARegister on fpga_init.

    Then, on fpga_read and fpga_write you check the permissions and

    • if the operetion is allowed, cast back the FPGARegister from the argument to a FPGARegisterReal, execute the desired action (set or read the value) and return a success code
    • if the operation is not allowed, just return an error code

    This way, no one including the header file will be able to access the FPGARegisterReal structure, and thus it will not have direct access to the register address. Obviously, one could hack it, but I'm quite sure that such intentional hacks are not your actual concerns.

提交回复
热议问题