如何在c代码中使用tcl apis [英] How to use tcl apis in a c code

查看:27
本文介绍了如何在c代码中使用tcl apis的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to use some of the functionalities(APIs) of my tcl code in another "c" code file. But i am not getting how to do that especiallly how to link them. For that i have taken a very simple tcl code which contains one API which adds two numbers and prints the sum. Can anybody tell me how can i call this tcl code to get the sum. How can i write a c wrapper that will call this tcl code. Below is my sample tcl program that i am using :

#!/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 库创建一个解释器来保存执行上下文.另外,您真的应该做一些工作来检索结果并将其打印出来(打印出脚本错误尤其重要,因为这有助于很多调试!)

To evaluate a script from C code, use Tcl_Eval() or one of its close relatives. In order to use that API, you need to link in the Tcl library, initialize the Tcl library and create an interpreter to hold the execution context. Plus you really ought to do some work to retrieve the result and print it out (printing script errors out is particularly important, as that helps a lot with debugging!)

因此,你会得到这样的结果:

Thus, you get something like this:

#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);
}

这篇关于如何在c代码中使用tcl apis的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆