How to use tcl apis in a c code

后端 未结 2 1786
隐瞒了意图╮
隐瞒了意图╮ 2021-01-24 10:42

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 take

2条回答
  •  不要未来只要你来
    2021-01-24 11:24

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

提交回复
热议问题