systemc

SystemC - Can I retrieve clock period from sc_in_clk port?


Can I retrieve the clock period through sc_port?

The following code doesn't work. I'd like to call method period() defined in sc_clock.

sc_in_clk clk;

*clk.get_interface()->period();

Solution

  • You could use dynamic_cast<> to cast the sc_interface returned by get_interface() as an sc_clock:

    #include <iostream>
    #include <systemc>
    
    using namespace std;
    using namespace sc_core;
    
    SC_MODULE(A) {
        sc_in_clk clk;
    
        SC_CTOR(A) {}
    
        void start_of_simulation() {
            sc_clock *channel = dynamic_cast<sc_clock *>(clk.get_interface());
            cout << name() << ": period is "
                 << (channel ? channel->period() : SC_ZERO_TIME) << endl;
        }
    };
    
    int sc_main(int argc, char *argv[]) {
        A a1("a1");
        A a2("a2");
    
        sc_clock clk("clk", 3.0, SC_NS);
        sc_signal<bool> fake_clk("fake_clk");
    
        a1.clk(clk);
        a2.clk(fake_clk);
    
        sc_start(10, SC_NS);
    
        return EXIT_SUCCESS;
    }
    

    This works because sc_clock is a subclass of sc_interface.

    If dynamic_cast<> succeeds, then a valid sc_clock pointer is returned. If it fails, NULL is returned.