Schedule with Python Bindings

211 views
Skip to first unread message

Shyam Parekh

unread,
Mar 3, 2023, 3:03:07 PM3/3/23
to ns-3-users
I'm trying to schedule execution of a python function at a later time using ns.Simulator.Schedule. For example,

def my_function():
  print("Hello from a function")t,
ns.Simulator.Schedule(ns.Seconds(5), my_function)

This doesn't work. Looks like, a pointer to my_function is needed on the C++ side. I don't know how to do that. Can you please suggest a way around?

FYI, I get the following error:

Traceback (most recent call last):
  File "/home/shyam/repos1/ns-3-allinone/ns-3.37/scratch/lena-simple-try.py", line 10, in <module>
    ns.Simulator.Schedule(ns.Seconds(5), my_function)
TypeError: Template method resolution failed:
  static ns3::EventId ns3::Simulator::Schedule(const ns3::Time& delay, const ns3::Ptr<ns3::EventImpl>& event) =>
    TypeError: could not convert argument 2
  Failed to instantiate "Schedule(ns3::Time&,function)"
  Failed to instantiate "Schedule(ns3::Time*,function)"
  Failed to instantiate "Schedule(ns3::Time,function)"
Command 'python3 /home/shyam/repos1/ns-3-allinone/ns-3.37/scratch/lena-simple-try.py' returned non-zero exit status 1.

Thanks,

Shyam

Gabriel Ferreira

unread,
Mar 3, 2023, 4:59:11 PM3/3/23
to ns-3-users
def callback():
            print("ello") 

ns.cppyy.cppdef("""
            EventImpl* pythonMakeEvent(void (*f)())
            {
                return MakeEvent(f);
            }
        """)
event = ns.cppyy.gbl.pythonMakeEvent2(callback) 
ns.Simulator.Schedule(ns.Seconds(123), event)

Shyam Parekh

unread,
Mar 3, 2023, 5:43:56 PM3/3/23
to ns-3-users
Wow! Thanks Gabriel! This works (after a small change: pythonMakeEvent2 to pythonMakeEvent)!

I spent half a day on this, did take a look at utils/python-unit-tests.py, but still couldn't make it to work.

BTW, as time permits, I'll try to compile all the "tricks" you're showing me in an informal document, and share it for the benefit of the community.

Shyam

Gabriel Ferreira

unread,
Mar 3, 2023, 10:01:24 PM3/3/23
to ns-3-users
All of these are already in the docs of a pending MR https://gitlab.com/nsnam/ns-3-dev/-/merge_requests/1277

I'm planning to add a few examples with jupyter notebooks, but haven't had the time for that.

Shyam Parekh

unread,
Mar 8, 2023, 5:22:12 PM3/8/23
to ns-3-users
Thanks Gabriel!
Reply all
Reply to author
Forward
0 new messages