0

In NS2, is there any way to embed a C++ variable into the TCL script? For example, in TCL, set routing protocol like this, set opt(rt) XXX XXX could be a variable which is defined in C++ program, such as

if(CONDITION==1) 

     XXX = "FLOODING";

if(CONDITION==2) 

         XXX = "AODV";

...
1
  • You're after a way to couple a variable in the two languages? Or are you after doing string manipulations to generate source code? I'll assume the former; the latter is boring… Commented Jan 11, 2012 at 15:48

1 Answer 1

1

The easiest way is to use Tcl_LinkVar to couple the char* variable in C++ (std::string not supported) to Tcl. Like that, all you have to do is change the C++ variable and call Tcl_UpdateLinkedVar to allow Tcl to notice that the variable has changed. You do not need to use Tcl_UpdateLinkedVar if you never have any traces set on the variable, but they're actually quite a common mechanism so doing the call is advised. Be aware that Tcl_UpdateLinkedVar is a reentrant call to the Tcl interpreter; some care should be taken to ensure that any traces you run do not trigger a loop back into your code…

// Setup (done once)...
Tcl_LinkVar(interp, "XXX", &XXX, TCL_LINK_STRING|TCL_LINK_READ_ONLY);


// Your code ...
if(CONDITION==1) 
     XXX = "FLOODING";
if(CONDITION==2) 
     XXX = "AODV";
// Notify Tcl ...
Tcl_UpdateLinkedVar(interp, "XXX");

If you want the setting of the Tcl variable XXX to change the C++ variable XXX, you need to take extra care. Drop the use of the TCL_LINK_READ_ONLY and ensure that you always use ckalloc to allocate memory for the strings in XXX (because Tcl will use the matched ckfree to dispose of the old one when setting the C++ variable).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.