SystemVerilog Class Handle

什么是类句柄?

诸如下面的pkt之类的类变量只是该对象已知的名称。 它可以保存类Packet的对象的句柄,但是在分配给对象之前,它始终为null。 此时,该类对象尚不存在。
类句柄示例:

//使用一个变量count创建一个新类
// 变量count存储整数值
class Packet;
  int count;
endclass
 
module tb;
  Packet pkt;//pkt为类变量,该类变量为对象已知的名称,用来保存类对象的句柄,在分配对象前始终为null,即此时该类的对象还不存在
 
    initial begin
      if (pkt == null)
        $display ("Packet handle 'pkt' is null");
 
      // 使用“句柄”显示类成员
      // 因为pkt不是对象,所以会出现运行时错误
      // 但是,仍然指向NULL。所以pkt不知道它应该持有一个成员
      $display ("count = %0d", pkt.count);
    end
endmodule
Simulation Log
ncsim> run
Packet handle 'pkt' is null
count = ncsim: *E,TRNULLID: NULL pointer dereference.
          File: ./testbench.sv, line = 18, pos = 33
         Scope: tb
          Time: 0 FS + 0

./testbench.sv:18       $display ("count = %0d", pkt.count);
ncsim> exit

什么是类对象?

仅当调用new()函数时才创建该类的实例。要再次引用该特定对象,我们需要将其句柄分配给Packet类型的变量。 类对象示例:

class Packet;
  int count;
endclass
 
module tb;
  Packet pkt;//类变量,对象的名称,用于存储变量的句柄
 
    initial begin
      if (pkt == null)//未使用new()函数分配空间,此时pkt指向null,未创建对象
        $display ("Packet handle 'pkt' is null");
 
      if (pkt == null)
      pkt = new();// 调用此类的new()函数,为句柄pkt分配空间,创建类packet的对象
        $display ("What's wrong, pkt is still null ?");
      else
        $display ("Packet handle 'pkt' is now pointing to an object, and not NULL");
 
      // 使用“句柄”显示类成员
      $display ("count = %0d", pkt.count);
    end
endmodule
Simulation Log
ncsim> run
Packet handle 'pkt' is null
Packet handle 'pkt' is now pointing to an object, and not NULL
count = 0
ncsim: *W,RNQUIE: Simulation is complete.

当两个手柄都指向同一个对象时会发生什么?

如果我们将pkt分配给名为pkt2的新变量,则新变量还将指向pkt中的内容。

class Packet;
  int count;
endclass
 
module tb;
    // 为类Packet创建两个“句柄”
    // 注意:这些“句柄”现在指向NULL
  Packet pkt, pkt2;
 
    initial begin
 
 
      // 调用此类的new()函数并为成员分配一些值
      pkt = new();
      pkt.count = 16'habcd;
      $display ("[pkt] count = 0x%0h", pkt.count);
 
      //使pkt2句柄指向pkt并打印成员变量
      pkt2 = pkt;
      $display ("[pkt2] count = 0x%0h", pkt2.count);
    end
endmodule
Simulation Log
ncsim> run
[pkt] count = 0xabcd
[pkt2] count = 0xabcd
ncsim: *W,RNQUIE: Simulation is complete.

参考文献:
【1】https://www.chipverify.com/systemverilog/systemverilog-class-constructor

发布了91 篇原创文章 · 获赞 7 · 访问量 5278

猜你喜欢

转载自blog.csdn.net/qq_43042339/article/details/104436640
今日推荐