如何插入 C++变量进入TCL脚本程序?
在NS2中,有没有办法将C++变量嵌入到TCL脚本中?例如,在TCL中,这样设置路由协议,set opt(rt) XXX
XXX
可以是一个在C++程序中定义的变量,例如
if(CONDITION==1)
XXX = "FLOODING";
if(CONDITION==2)
XXX = "AODV";
...
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";
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单的方法是使用
Tcl_LinkVar
将 C++ 中的 char* 变量(不支持 std::string)耦合到 Tcl。像这样,您所要做的就是更改 C++ 变量并调用 Tcl_UpdateLinkedVar 让 Tcl 注意到变量已更改。如果您从未在变量上设置任何跟踪,则不需要使用 Tcl_UpdateLinkedVar,但它们实际上是一种非常常见的机制,因此建议进行调用。请注意,Tcl_UpdateLinkedVar
是对 Tcl 解释器的可重入调用;应该注意确保您运行的任何跟踪都不会触发代码中的循环...如果您希望 Tcl 变量
XXX
的设置更改 C++ 变量XXX,需要格外小心。放弃使用 TCL_LINK_READ_ONLY 并确保始终使用
ckalloc
为XXX
中的字符串分配内存(因为在设置 C++ 变量时,Tcl 将使用匹配的 ckfree 来处理旧的)。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 callTcl_UpdateLinkedVar
to allow Tcl to notice that the variable has changed. You do not need to useTcl_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 thatTcl_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…If you want the setting of the Tcl variable
XXX
to change the C++ variableXXX
, you need to take extra care. Drop the use of the TCL_LINK_READ_ONLY and ensure that you always useckalloc
to allocate memory for the strings inXXX
(because Tcl will use the matchedckfree
to dispose of the old one when setting the C++ variable).