1

我想在另一个“c”代码文件中使用我的 tcl 代码的一些功能(API)。但我不知道如何做到这一点,尤其是如何链接它们。为此,我采用了一个非常简单的 tcl 代码,其中包含一个 API,它将两个数字相加并打印总和。谁能告诉我如何调用这个 tcl 代码来得到总和。我如何编写将调用此 tcl 代码的 ac 包装器。下面是我正在使用的示例 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 ......."

}
4

2 回答 2

4

要从 C 代码评估脚本,请使用Tcl_Eval()或其近亲之一。为了使用该 API,您需要链接 Tcl 库,初始化 Tcl 库创建一个解释器来保存执行上下文。另外,您确实应该做一些工作来检索结果并将其打印出来(打印脚本错误特别重要,因为这对调试有很大帮助!)

因此,你会得到这样的东西:

#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);
}
于 2012-12-13T09:58:23.610 回答
0

我想我已经摆脱了它。你是对的。问题出在我使用的包含方法上。我有文件 tcl.h、tclDecls.h 和 tclPlatDecls.h 包含在 c 代码中,但这些文件在路径 /usr/include 中不存在,所以我将这些文件复制到该目录,可能不是正确的办法。最后我没有将这些文件复制到 /usr/include 并在编译时给出了包含路径。我已经创建了可执行文件,它在终端上给出了正确的结果。谢谢你的帮助。

这是我正在使用的确切 c 代码:

#include <tcl.h>
#include <tclDecls.h>
#include <tclPlatDecls.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main (int argc, char **argv) {
Tcl_Interp *interp;
int code;
char *result;

printf("inside main function \n");
//    Tcl_InitStubs(interp, "8.5", 0);
Tcl_FindExecutable(argv[0]);
interp = Tcl_CreateInterp();
code = Tcl_Eval(interp, "source simple_addition.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);

}

并编译此代码并生成可执行文件,我使用以下命令:

gcc simple_addition_wrapper_new.c -I/usr/include/tcl8.5/ -ltcl8.5 -o simple_addition_op

我已经执行了文件 simple_addition_op 并得到了以下正确的结果

inside main function 
c is 30 .......

我特别感谢 Donal Fellows 和 Johannes

于 2012-12-18T06:43:49.127 回答