我想在另一个“c”代码文件中使用我的 tcl 代码的一些功能(API)。但我不知道如何做到这一点,特别是如何链接它们。为此,我采用了一个非常简单的 tcl 代码,其中包含一个 API,该 API 将两个数字相加并打印总和。谁能告诉我如何调用这个 tcl 代码来获得总和。我如何编写一个 C 包装器来调用这个 tcl 代码。下面是我正在使用的示例 tcl 程序:
#!/usr/bin/env tclsh8.5
proc add_two_nos { } {
set a 10
set b 20
set c [expr { $a + $b } ]
puts " c is $c ......."
}
要从 C 代码评估脚本,请使用Tcl_Eval()或其近亲之一。为了使用该 API,您需要链接 Tcl 库,初始化Tcl库 and 创建一个解释器保存执行上下文。另外,您确实应该做一些工作来检索结果并将其打印出来(打印脚本错误尤其重要,因为这有助于lot并进行调试!)
因此,你会得到这样的结果:
#include <tcl.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
Tcl_Interp *interp;
int code;
char *result;
Tcl_FindExecutable(argv[0]);
interp = Tcl_CreateInterp();
code = Tcl_Eval(interp, "source myscript.tcl; add_two_nos");
/* Retrieve the result... */
result = Tcl_GetString(Tcl_GetObjResult(interp));
/* Check for error! If an error, message is result. */
if (code == TCL_ERROR) {
fprintf(stderr, "ERROR in script: %s\n", result);
exit(1);
}
/* Print (normal) result if non-empty; we'll skip handling encodings for now */
if (strlen(result)) {
printf("%s\n", result);
}
/* Clean up */
Tcl_DeleteInterp(interp);
exit(0);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)