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 write-only.
The write-only registers will produce undefined values when read.
I want to define a pointer type that will allow the compiler to detect when reading values from a write-only registers (a.k.a. dereferencing).
Can a write-only pointer be created using only C language syntax?
(We are developing first prototype using C, but moving to C++ on 2nd generation.)
How can an efficient write-only pointer be created in C++? (Remember, this is not tracking items in dynamic memory, but accessing hardware addresses.)
This code is used on an embedded system where safety and quality are highest concerns.
A void pointer can hold addresses of any type and can be typecast to any type. It is also called a generic pointer and does not have any standard data type.
The Data type is needed when dereferencing the pointer so it knows how much data it should read. For example dereferencing a chart pointer should read the next byte from the adress it is pointing to while an int pointer should read 2 bytes.
In C++, a pointer refers to a variable that holds the address of another variable. Like regular variables, pointers have a data type. For example, a pointer of type integer can hold the address of a variable of type integer. A pointer of character type can hold the address of a variable of character type.
Pointers are used extensively in both C and C++ for three main purposes: to allocate new objects on the heap, to pass functions to other functions. to iterate over elements in arrays or other data structures.
I'd probably write a tiny wrapper class for each:
template <class T> class read_only { T volatile *addr; public: read_only(int address) : addr((T *)address) {} operator T() volatile const { return *addr; } }; template <class T> class write_only { T volatile *addr; public: write_only(int address) : addr ((T *)address) {} // chaining not allowed since it's write only. void operator=(T const &t) volatile { *addr = t; } };
At least assuming your system has a reasonable compiler, I'd expect both of these to be optimized so the generated code was indistinguishable from using a raw pointer. Usage:
read_only<unsigned char> x(0x1234); write_only<unsigned char> y(0x1235); y = x + 1; // No problem x = y; // won't compile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With