2

I have a structure x defined as below

typedef struct packed {
  int a;
  int b;
} x_s;

The number of members inside the structure is not deterministic. I want to print out each value of the structure member separately. Is there a way to loop through the structure members?

Thanks in advance.

2 Answers 2

2

You can try

$display("x: %p",x); 

%p is for an assignment pattern. and displays

 x:'{a:0, b:0}

If you want anything more complex, there's no way to iterate over struct members from the SystemVerilog itself. There is a C based API (VPI) to get access to this information, but you need to be a serious developer to do this.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. I tried doing this inside a class. It just printed %p without the value. Is there any restriction of where it can be used?
class transaction_class; typedef struct packed { int a; int b; } member; member mem, dont_compare; function new; this.dont_compare = '0; endfunction function compare(transaction_class _actual); if((this.mem & ~this.dont_compare) != (_actual.mem & ~this.dont_compare)) $error("Compare mismatch. expected is %p and actual is %p\n", this.mem, _actual.mem); else $display("Compare success\n"); endfunction endclass Displayed: Compare mismatch. expected is %p and actual is %p
Looks like a tool issue. Some tools do not support %p in $error, only $display or $sformatf. Also, your compare function needs a void return type. Implicit default return type is one logic bit.
glad to know using VPI makes me "a serious developer" :D
0

A cumbersome way to iterate over a struct can be to use a union to contain the struct. It is a tedious way but gets the intent of cycling over a struct.

typedef struct packed {
  int a;
  int b;
} x_s;
typedef enum {a, b} x_e;  //not needed but just helps in identifying the struct members 
typedef union {
  x_s x;
  int xs[2];  //2 because of 2 integer members of the struct
} x_u;

virtual function void cycle_thru_struct();
  x_e v_e;
  x_u v_u;
  v_u.x.a = 10;
  v_u.x.b = 20;

  //One way is this but no way to know the name of the struct member
  foreach (v_u.xs[i]) begin
    `uvm_info("cycle_thru_struct", $sformatf("struct-member[%d] = %0d", i , v_u.xs[i]), UVM_MEDIUM)
  end

  //Other way is this where an enum needs to carry the struct member names
  for(int i=0; i< v_e.num(); i++) begin
    `uvm_info("cycle_thru_struct", $sformatf("%s : 0x%x", v_e.name(), v_u.xs[i]), UVM_MEDIUM)
     v_e = v_e.next();
  end

endfunction : cycle_thru_struct

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.