SystemVerilog class:验证平台的基本构件

class 是 SystemVerilog 面向对象建模的基础。它把数据与操作封装在一起,通过句柄引用对象,支持继承与多态,是构建可复用 testbench 的核心。

1. 声明与实例化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class packet;
rand bit [31:0] addr;
rand bit [31:0] data;

function void print();
$display("addr=%0h data=%0h", addr, data);
endfunction
endclass

packet p; // 句柄,默认 null
initial begin
p = new(); // 构造对象
p.print();
end

new() 分配对象并返回句柄;未调用 new() 前访问成员会报空句柄错误。

2. class 与 struct

特性 class struct
存储 堆上对象,句柄引用 值类型,直接存储
赋值 句柄拷贝(共享同一对象) 内容拷贝
继承 支持 不支持
可综合性 否 packed 可综合

理解“句柄赋值是共享”这一点,能避免大量“改了一个副本,另一个没变”的困惑。

3. 生命周期

对象由 new() 创建,当最后一个句柄失效时由仿真器回收。验证平台中通常把对象放进队列或 mailbox,由 scoreboard 持有,生命周期覆盖整个测试。

小结

class 的价值是“把事务变成对象”。先想清楚谁持有句柄、何时 new、何时释放,再写成员函数。

参考文献:ChipVerify SystemVerilog Tutorial — SystemVerilog Class 章节(https://chipverify.com/systemverilog/systemverilog-class)。本文为原创中文讲解。