For an embedded design I want to place a C std::array at a specific memory address, which points to a buffer shared by hardware and software. Is this possible?
CodePudding user response:
Try Placement new:
#include <array>
#include <iostream>
int main()
{
alignas(double) char buffer[100];
auto parr = new (buffer) std::array<double, 3> {3.14, 15.161, 12};
const auto & arr = *parr;
std::cout << (void*) &arr << " " << (void*) buffer << "\n";
for (auto x: arr)
std::cout << x << " ";
std::cout << "\n";
}
which may give this output:
0x7ffcdd906770 0x7ffcdd906770
3.14 15.161 12
One thing to be worried about is whether the address you want to use is consistent with the alignment requirements of the data you want to hold in the array. Most likely you will be dealing with char
s, float
s or int
s, so this condition shouldn't be difficult to enforce.
CodePudding user response:
For embedded code, two simple solutions spring to mind:
- Declare
extern int myArray[1234] ;
and then definemyArray
(or rather its mangled form) in your linker definition file. - Define a macro:
#define myArray ((int*)0xC0DEFACE)
The first solution is for the purists; the second is for the pragmatists.