bindings: Remove CreateObject/GetObject tricks

This commit is contained in:
Gabriel Ferreira
2024-05-18 16:54:03 -03:00
parent 4a0091ba6c
commit 7711e5290e
9 changed files with 29 additions and 102 deletions

View File

@@ -560,81 +560,6 @@ def load_modules():
)
setattr(cppyy.gbl.ns3, "LookupByNameFailSafe", cppyy.gbl.LookupByNameFailSafe)
def CreateObject(className):
try:
try:
func = "CreateObject%s" % re.sub("[<|>]", "_", className)
return getattr(cppyy.gbl, func)()
except AttributeError:
pass
try:
func = "Create%s" % re.sub("[<|>]", "_", className)
return getattr(cppyy.gbl, func)()
except AttributeError:
pass
raise AttributeError
except AttributeError:
try:
func = "CreateObject%s" % re.sub("[<|>]", "_", className)
cppyy.cppdef(
"""
using namespace ns3;
Ptr<%s> %s(){
Ptr<%s> object = CreateObject<%s>();
return object;
}
"""
% (className, func, className, className)
)
except Exception as e:
try:
func = "Create%s" % re.sub("[<|>]", "_", className)
cppyy.cppdef(
"""
using namespace ns3;
%s %s(){
%s object = %s();
return object;
}
"""
% (className, func, className, className)
)
except Exception as e:
exit(-1)
return getattr(cppyy.gbl, func)()
setattr(cppyy.gbl.ns3, "CreateObject", CreateObject)
def GetObject(parentObject, aggregatedObject):
# Objects have __cpp_name__ attributes, so parentObject
# should not have it while aggregatedObject can
if hasattr(parentObject, "__cpp_name__"):
raise Exception("Class was passed instead of an instance in parentObject")
aggregatedIsClass = hasattr(aggregatedObject, "__cpp_name__")
aggregatedIsString = type(aggregatedObject) == str
aggregatedIsInstance = not aggregatedIsClass and not aggregatedIsString
if aggregatedIsClass:
aggregatedType = aggregatedObject.__cpp_name__
if aggregatedIsInstance:
aggregatedType = aggregatedObject.__class__.__cpp_name__
if aggregatedIsString:
aggregatedType = aggregatedObject
cppyy.cppdef(
"""using namespace ns3; template <> Ptr<%s> getAggregatedObject<%s>(Ptr<Object> parentPtr, %s param)
{
return parentPtr->GetObject<%s>();
}
"""
% (aggregatedType, aggregatedType, aggregatedType, aggregatedType)
)
return cppyy.gbl.getAggregatedObject(
parentObject, aggregatedObject if aggregatedIsClass else aggregatedObject.__class__
)
setattr(cppyy.gbl.ns3, "GetObject", GetObject)
return cppyy.gbl.ns3

View File

@@ -47,7 +47,7 @@ def main():
# mu, var = 100, 225
## Random number generator.
rng = ns.CreateObject("NormalRandomVariable")
rng = ns.CreateObject[ns.NormalRandomVariable]()
rng.SetAttribute("Mean", ns.DoubleValue(100.0))
rng.SetAttribute("Variance", ns.DoubleValue(225.0))

View File

@@ -119,7 +119,7 @@ def main(argv):
cmd.Parse(argv)
model = ns.cppyy.gbl.MyModel()
v = ns.CreateObject("UniformRandomVariable")
v = ns.CreateObject[ns.UniformRandomVariable]()
v.SetAttribute("Min", ns.DoubleValue(10))
v.SetAttribute("Max", ns.DoubleValue(20))

View File

@@ -40,8 +40,8 @@ def main(argv):
ns.LogComponentEnable("GenericBatteryModel", ns.LOG_LEVEL_DEBUG)
node = ns.Node()
batteryHelper = ns.energy.GenericBatteryModelHelper()
batteryModel = ns.CreateObject("GenericBatteryModel")
batteryHelper = ns.GenericBatteryModelHelper()
batteryModel = ns.CreateObject[ns.energy.GenericBatteryModel]()
devicesEnergyModel = ns.energy.SimpleDeviceEnergyModel()
batteryModel.SetAttribute("FullVoltage", ns.DoubleValue(1.39)) # Vfull
@@ -57,7 +57,9 @@ def main(argv):
batteryModel.SetAttribute("TypicalDischargeCurrent", ns.DoubleValue(1.3)) # i typical
batteryModel.SetAttribute("CutoffVoltage", ns.DoubleValue(1.0)) # End of charge.
batteryModel.SetAttribute("BatteryType", ns.EnumValue(ns.NIMH_NICD)) # Battery type
batteryModel.SetAttribute(
"BatteryType", ns.EnumValue[ns.energy.GenericBatteryType](ns.energy.NIMH_NICD)
) # Battery type
devicesEnergyModel.SetEnergySource(batteryModel)
batteryModel.AppendDeviceEnergyModel(devicesEnergyModel)

View File

@@ -18,4 +18,6 @@ cpp_examples = [
# (example_name, do_run).
#
# See test.py for more information.
python_examples = []
python_examples = [
("generic-battery-discharge-example.py", "True"),
]

View File

@@ -1,5 +1,3 @@
from __future__ import division
import os
import sys

View File

@@ -52,9 +52,9 @@ def main(argv):
cmd.AddValue("Plot", "Plot the results using the matplotlib python module", Plot)
cmd.Parse(argv)
wifi = ns.CreateObject("WifiHelper")
wifiMac = ns.CreateObject("WifiMacHelper")
wifiPhy = ns.CreateObject("YansWifiPhyHelper")
wifi = ns.WifiHelper()
wifiMac = ns.WifiMacHelper()
wifiPhy = ns.YansWifiPhyHelper()
wifiChannel = ns.YansWifiChannelHelper.Default()
wifiPhy.SetChannel(wifiChannel.Create())
ssid = ns.Ssid("wifi-default")
@@ -95,7 +95,7 @@ def main(argv):
container = ns.NodeContainer(node)
internet.Install(container)
mobility = ns.CreateObject("ConstantPositionMobilityModel")
mobility = ns.CreateObject[ns.ConstantPositionMobilityModel]()
mobility.SetPosition(ns.Vector(xi * DISTANCE, yi * DISTANCE, 0))
node.AggregateObject(mobility)
@@ -112,7 +112,7 @@ def main(argv):
)
container = ns.NodeContainer(node)
app = onOffHelper.Install(container)
urv = ns.CreateObject("UniformRandomVariable") # ns.cppyy.gbl.get_rng()
urv = ns.CreateObject[ns.UniformRandomVariable]() # ns.cppyy.gbl.get_rng()
startDelay = ns.Seconds(urv.GetValue(20, 30))
app.Start(startDelay)
@@ -209,7 +209,7 @@ def main(argv):
print(res)
if Plot.value:
import pylab
from matplotlib import pyplot as plt
delays = []
for flow_id, flow_stats in monitor.GetFlowStats():
@@ -217,10 +217,10 @@ def main(argv):
if tupl.protocol == 17 and tupl.sourcePort == 698:
continue
delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets)
pylab.hist(delays, 20)
pylab.xlabel("Delay (s)")
pylab.ylabel("Number of Flows")
pylab.show()
plt.hist(delays, 20)
plt.xlabel("Delay (s)")
plt.ylabel("Number of Flows")
plt.show()
return 0

View File

@@ -53,7 +53,7 @@ for i in range(4):
switchNode = csmaSwitch.Get(0)
swtch = ns.OpenFlowSwitchHelper()
controller = ns.ofi.DropController()
# controller = ns.CreateObject("ns3::ofi::LearningController")
# controller = ns.CreateObject[ns.ofi.LearningController]()
swtch.Install(switchNode, switchDevices, controller)
# controller->SetAttribute("ExpirationTime", TimeValue(timeout))

View File

@@ -212,7 +212,7 @@ class TestSimulator(unittest.TestCase):
"""
nc = ns.NodeContainer(1)
node = nc.Get(0)
internet = ns.CreateObject("InternetStackHelper")
internet = ns.InternetStackHelper()
internet.Install(node)
self._received_packet = None
@@ -251,8 +251,8 @@ class TestSimulator(unittest.TestCase):
@param self this object
@return None
"""
# Templated class DropTailQueue<Packet> in C++
queue = ns.CreateObject("DropTailQueue<Packet>")
# Templated class DropTailQueue[ns.Packet] in C++
queue = ns.CreateObject[ns.DropTailQueue[ns.Packet]]()
queueSizeValue = ns.QueueSizeValue(ns.QueueSize("500p"))
queue.SetAttribute("MaxSize", queueSizeValue)
@@ -261,8 +261,8 @@ class TestSimulator(unittest.TestCase):
self.assertEqual(limit.Get(), ns.QueueSize("500p"))
## -- object pointer values
mobility = ns.CreateObject("RandomWaypointMobilityModel")
ptr = ns.CreateObject("PointerValue")
mobility = ns.CreateObject[ns.RandomWaypointMobilityModel]()
ptr = ns.PointerValue()
mobility.GetAttribute("PositionAllocator", ptr)
self.assertEqual(ptr.GetObject(), ns.Ptr["Object"](ns.cppyy.nullptr))
@@ -270,7 +270,7 @@ class TestSimulator(unittest.TestCase):
ptr.SetObject(pos)
mobility.SetAttribute("PositionAllocator", ptr)
ptr2 = ns.CreateObject("PointerValue")
ptr2 = ns.PointerValue()
mobility.GetAttribute("PositionAllocator", ptr2)
self.assertNotEqual(ptr.GetObject(), ns.Ptr["Object"](ns.cppyy.nullptr))
@@ -282,8 +282,8 @@ class TestSimulator(unittest.TestCase):
@param self this object
@return None
"""
csma = ns.CreateObject("CsmaNetDevice")
channel = ns.CreateObject("CsmaChannel")
csma = ns.CreateObject[ns.CsmaNetDevice]()
channel = ns.CreateObject[ns.CsmaChannel]()
csma.Attach(channel)
c1 = csma.GetChannel()