SystemVerilog dynamic cast:$cast 与类型转换

$cast 在运行时检查对象类型兼容性,是 SystemVerilog 中唯一安全的向下转型手段。它失败时返回 0,不会像 C++ 那样产生未定义行为。

1. 句柄转换

1
2
3
4
5
6
7
base_txn b;
derived_txn d;

if ($cast(d, b))
d.print();
else
`uvm_error("CAST", "b is not derived_txn")

$cast(目标句柄, 源句柄) 成功时把源句柄赋给目标并返回 1;失败返回 0,目标句柄保持不变。

2. 与 static cast

$cast 做运行时检查;type'(expr) 是编译期强制转换,不检查兼容性。跨继承层次向下转型必须用 $cast。

3. 常见模式

  • scoreboard 收到基类句柄后转成具体事务类型。
  • 工厂创建对象后按类型分支处理。
  • 错误注入时把正常事务转为错误事务。

4. 常见误区

  1. 用 type'() 做向下转型:可能得到非法句柄。
  2. 忽略返回值:转换失败后继续使用目标句柄。
  3. 期望 $cast 转换基本类型之间的任意值:它主要用于类句柄。

小结

$cast 是运行时类型检查器。向下转型前先问:这个对象真的是派生类型吗?让 $cast 替你回答。

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