Anil Bisht
Anil Bisht

Reputation: 65

How to send a tcl command to a tcl/tk interpreter from a C application

I am struggling with a problem and will appreciate your help.

Let's assume I have a tcl/tk application and interpreter 'x.y.123.3454' and I want to send some tcl procedures, which is defined in the 'x.y.123.3454', from a C application.

For example, I want to send puts "Hello World" from the C application to 'x.y.123.3454'. How to do it?

If you are wondering, why I am not running those procedures & commands directly in that tcl interpreter, please let me know.

Upvotes: 0

Views: 796

Answers (2)

Anil Bisht
Anil Bisht

Reputation: 65

After spending a good amount of time on this issue, I realized that there is no easy way to send a tcl command from C to an already existing tcl/tk application or interpreter.

Following link concurs: http://cpptk.sourceforge.net/doc.html

Upvotes: 0

Donal Fellows
Donal Fellows

Reputation: 137567

On the C level, a Tcl interpreter is represented by a handle of type Tcl_Interp * (which should be treated as if it points to an opaque structure). It's conventionally given the name interp by people working with the Tcl API, but that isn't really very important. Once you have such a handle, you use:

int returnCode = Tcl_Eval(interp, "puts \"Hello World\"");

to run some code (the backslashes are there because we're putting double quotes inside a C string constant). The return code is going to be equal to TCL_OK if the execution finished successfully, and will equal TCL_ERROR if there was something that went wrong. In the OK case, you get the result value with Tcl_GetObjResult(interp) (and you can use Tcl_GetString on that to get the string version of the result for printing). In the error case, you use the same functions (i.e., Tcl_GetObjResult, Tcl_GetString) to retrieve the error message. There are other return codes possible, but you won't usually see them.

Of course, the result of puts is the empty string on success; the message is printed out, not returned.


How do you get that interpreter handle? Well, it really depends on how your code is integrating with Tcl. If you're writing a shared library that Tcl will load, it's the sole argument to your initialisation function. On the other hand, if you're embedding Tcl then you're probably calling Tcl_CreateInterp() at some point, which returns the handle to a newly-created interpreter. It's usually pretty obvious which you're doing.

Upvotes: 1

Related Questions