Rella
Rella

Reputation: 66935

C++/Tk how to exequte general tcl code?

So we have code like:

#include "cpptk.h"
#include <stdio.h>

using namespace Tk;

void hello() {
     puts("Hello C++/Tk!");
}

int main(int, char *argv[])
{
    static char* str = "button .a -text "Say Hello ppure TCL"\n"
                   "pack .a\n";
     init(argv[0]);

     button(".b") -text("Say Hello") -command(hello);
     pack(".b") -padx(20) -pady(6);

     runEventLoop();
}

imagine str is complex tcl code. We want to feed it to C++/Tk as a string. Also we want to have it exequted in the same TCL vm our general C++/Tk programm with gui we created in C++/Tk code runs. So the result of this code would be 2 buttons inside a window. How to do such thing?

How to do such thing?

Upvotes: 1

Views: 215

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137567

Have you got access to the Tcl_Interp* handle used inside C++/Tk? If so (and assuming here you've got it in a variable called interp) use:

int resultCode = Tcl_Eval(interp, str);

Next, check the resultCode to see if it is TCL_OK or TCL_ERROR (other values are possible, but uncommon in normal scripts). That tells you the interpretation of the “result”, which you get like this:

const char *result = Tcl_GetString(Tcl_GetObjResult(interp));

If the result code says its an error, result is now an error message. If it was ok, the result is the output of the script (NB: not what was written to standard out though). It's up to you what to do with that.


[EDIT]: I looked this up in more detail. It's nastier than it appears, because C++/Tk hides away Tcl quite deep inside itself. In so far as I can see, you do this (untested!):

#include "cpptk.h" // might need "base/cpptkbase.h" instead
#include <string>

// This next part is in a function or method...
std::string script("the script to evaluate goes here");
std::string result = Tk::details::Expr(script,true);

Upvotes: 2

Related Questions