Home > other >  Is it possible to place a std::array at a fixed memory address?
Is it possible to place a std::array at a fixed memory address?

Time:10-02

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 chars, floats or ints, so this condition shouldn't be difficult to enforce.

CodePudding user response:

For embedded code, two simple solutions spring to mind:

  1. Declare extern int myArray[1234] ; and then define myArray (or rather its mangled form) in your linker definition file.
  2. Define a macro: #define myArray ((int*)0xC0DEFACE)

The first solution is for the purists; the second is for the pragmatists.

  • Related