Hi,
I’m trying to develop a small util class that can take an associative array of any enum type and convert it to a semicolon separated string. Example:
typedef enum { APPLES, ORANGES, GRAPES } fruit_e;
fruit_e my_fruit[] = { APPLES, GRAPES, APPLES, ORANGES };
I would like to convert my_fruit to “APPLES; GRAPES; APPLES; ORANGES”.
What I had in mind is using a parameterized util class that has a static method that accepts the array and returns the string. Something like:
class my_array_concat #(type T);
static function string to_str(T array[]);
string str;
foreach (array[n]) begin
str = { str, "; ", array[n].name() };
end
endfunction
endclass
This doesn’t work because it can’t find the name() function. Is there any way to qualify the parameter as always being an enum so that the name() function is visible? Also if there is a better way to do this (the conversion I mean), I wouldn’t mind using that.
Thanks,
Tudor
What you are doing should be fine. Here is a complete example (including a return in the function so that you don’t get an empty string result) and some handling of the first element. I’ve verified that this works in Questa 10.0 and later so if you are still having problems, you might want to contact support for whichever simulator you are using or try a later version of the simulator.
Gord
module top;
typedef enum { APPLES, ORANGES, GRAPES } fruit_e;
fruit_e my_fruit[] = { APPLES, GRAPES, APPLES, ORANGES };
class my_array_concat #(type T);
static function string to_str(T array[]);
string str;
bit first = 1;
foreach (array[n]) begin
str = first ? array[n].name() : { str, "; ", array[n].name() };
first = 0;
end
return str;
endfunction
endclass
string s = my_array_concat#(fruit_e)::to_str(my_fruit);
initial $display(s);
endmodule
run -all
APPLES; GRAPES; APPLES; ORANGES
quit
This worked for me after correcting your function
module top;
class my_array_concat #(type T);
static function string to_str(T array[]);
to_str="";
foreach (array[n]) begin
if (to_str == "")
to_str = array[n].name();
else
to_str = { to_str, ";", array[n].name() };
end
endfunction
endclass
typedef enum { APPLES, ORANGES, GRAPES } fruit_e;
fruit_e my_fruit[] = { APPLES, GRAPES, APPLES, ORANGES };
initial $display(my_array_concat#(fruit_e)::to_str(my_fruit));
endmodule
produces
# APPLES;GRAPES;APPLES;ORANGES
The compiler will enforce that my_array_concat is passed an enum type by giving you a compiler error if it is not a type with a name() method.