如何插入 C++变量进入TCL脚本程序?

发布于 2024-12-25 20:47:28 字数 233 浏览 3 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

許願樹丅啲祈禱 2025-01-01 20:47:28

最简单的方法是使用 Tcl_LinkVar 将 C++ 中的 char* 变量(不支持 std::string)耦合到 Tcl。像这样,您所要做的就是更改 C++ 变量并调用 Tcl_UpdateLinkedVar 让 Tcl 注意到变量已更改。如果您从未在变量上设置任何跟踪,则不需要使用 Tcl_UpdateLinkedVar,但它们实际上是一种非常常见的机制,因此建议进行调用。请注意,Tcl_UpdateLinkedVar 对 Tcl 解释器的可重入调用;应该注意确保您运行的任何跟踪都不会触发代码中的循环...

// 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");

如果您希望 Tcl 变量 XXX 的设置更改 C++ 变量 XXX,需要格外小心。放弃使用 TCL_LINK_READ_ONLY 确保始终使用 ckallocXXX 中的字符串分配内存(因为在设置 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 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文