Search code examples
vhdlhdl

Initialize dynamic VHDL array


--in the package
type t_array is array (natural range <>) of std_logic_vector (7 downto 0);
type p_array is access t_array;

--in my testbench
variable my_array : p_array := null;
begin
my_array := new t_array(0 to 19);
my_array := ( X"00",X"00",X"00",X"00",X"FF",
              X"FF",X"FF",X"FF",X"00",X"00",
              X"FF",X"FF",X"FF",X"FF",X"FF",
              X"FF",X"FF",X"FF",X"FF",X"FF" );

Error: Target type util_lib.tb_pkg.p_array in variable assignment is different from expression type util_lib.tb_pkg.t_array.

How can I compactly assign all the elements of the array?


Solution

  • (1). Dereference your poincough access type.

    my_array.all := (...);
    

    (2) Initialise it from a function

    begin
        my_array := new_array(20);
    

    The gory details of initialising it can be buried in the function, which could calculate the values algorithmically, copy them from a constant array, or even read the contents from file.

    constant initialiser : t_array := (...);
    
    function new_array(length : natural range initialiser'range) return t_array is
       variable temp : p_array := new t_array(0 to length - 1);
    begin
       -- either this
       for i in temp'range loop
          temp(i) := initialiser(i);
       end loop;
       -- or simply this
       temp.all := initialiser(temp'range);
       return temp;
    end new_array;
    

    (note the constraint on arguments to new_array : that ensures it won't create an array larger than the initialiser.)