OBJCMDWRITE(3tclx)

๐Ÿ’– TclCommandWriting โ€” Writing C language extensions to Tcl ๐Ÿ’–

okay bestie, this is the Command Writing(3tclx) page, and it's a long one so buckle up ๐ŸŽ€


โœจ OVERVIEW โœจ

So this doc is for you, the programmer who wants to extend Tcl with C language routines. It's also gonna be super helpful if you're trying to add Tcl to an existing editor, communications program, window manager, etc. And if you're already an experienced extension writer? This manual will lowkey help you rewrite your apps to use the new Tcl object system. ๐Ÿ’…

The ground rules: we're assuming you're already fluent in C, and that you've built and installed Tcl on your machine. No cap.

If you want the deets on the available C interface routines to Tcl, go look at the *.3 manual pages in the doc directory of the baseline Tcl distribution, and also the *.3 manpages in the doc directory of Extended Tcl. ๐Ÿ“š


๐ŸŒˆ TCL OBJECT SYSTEM ๐ŸŒˆ

Ever since Tcl version 8 dropped, Tcl has a whole new system for managing Tcl values internally. To the Tcl programmer, the new objects look and act like strings, same as always โ€” no drama there. But at the C level?? bestie, these objects can now also hold cached internal representations of the strings in various native datatypes. Like, an object holding a string that's an integer will now maintain a machine-code integer representation, if an integer representation has been needed. Using these objects is much more efficient than using the older-style Tcl strings โ€” although the older style is still (currently) supported. ๐Ÿ‘‘

So the object system has almost zero effect on how the Tcl programmer uses Tcl, right? But the object system's C interfaces to strings, integers, lists, etc., have changed considerably. Converting a package to the new system can be a lot of work, fr fr โ€” but the combination of the object system (which saves Tcl from constantly converting strings to integers and back, etc.) and the on-the-fly bytecode compiler (which keeps Tcl from having to continually reparse code it's about to execute) yields Tcl programs that routinely execute several times more quickly than with previous versions (Tcl 7 and before), and in some cases run as much as 2500 (!) times faster than before. NOT ME SCREAMING. ๐Ÿ˜ญ๐Ÿ”ฅ

So we chose to rewrite the Command Writer's manpage โ€” which has been shipping with Extended Tcl for a number of years โ€” to produce this new version based on the new object system. The old manpage, based on the older string-oriented routines, will still be included in TclX releases for now, since it's still relevant to Tcl releases through version 7, and may be of use to those modifying/upgrading packages written for the old model. The old manual will be dropped from the release once we deem it unneeded; the old interfaces should now be considered legacy interfaces, and all new development should be done using the new object interfaces, unless backwards compatibility to pre-Tcl-8 releases is needed. ๐Ÿ’€


๐Ÿฆ‹ A SIMPLE C EXTENSION ๐Ÿฆ‹

Every single C-based Tcl command gets called with four arguments:

  • a client data pointer
  • an interpreter pointer
  • an argument count
  • a pointer to an array of Tcl objects containing the arguments to the command

Here's a simple C extension to Tcl, described right below it:

#include "tcl.h"

int App_DumpArgsObjCmd(clientData, interp, objc, objv)
    void          *clientData;
    Tcl_Interp    *interp;
    int            objc;
    Tcl_Obj      **objv;
{
        int   i;
     int   stringLen;
     char *stringPtr;

        for (i = 1; i < objc; i++) {
          stringPtr = Tcl_GetStringFromObj (objv [i], &stringLen);
                printf("%s", stringPtr);
          if (i < objc - 1) printf(" ");
        }
        printf("\n");
        return TCL_OK;
}

The client data pointer gets described later, don't worry. ๐Ÿ™ˆ


๐ŸŒธ INTERPRETERS ๐ŸŒธ

The interpreter pointer is the ``key'' to an interpreter. It's returned by Tcl_CreateInterp and it's used extensively within Tcl, and your C extensions will be using it too. The data structure pointed to by the interpreter pointer, plus all the subordinate structures that branch off of it, make up a Tcl interpreter โ€” and that includes all of the currently defined procedures, commands, variables, arrays, and the execution state of that interpreter. ๐Ÿซถ

Wanna know more about creating and deleting interpreters? Go examine the CrtInterp(3) manpage in the core Tcl distribution. Want info on creating interpreters that include the commands provided by Extended Tcl? Check out the TclX_Init(3) manpage of Extended Tcl. And for a manual page describing the user-visible fields of a Tcl interpreter, please look at Interp(3) in core Tcl. โœจ

๐Ÿงš OBJECT COUNT AND ARGUMENTS ๐Ÿงš

The argument count โ€” or object count (objc) โ€” and the pointer to an array of pointers to Tcl objects of the command's arguments (objv) is handled by your C code, kinda similar to how you'd write a C main function. An argument count and array of pointers works the same as in a C main call; pointers to the arguments to the function are contained in the objv array. And just like a C main, the first argument (objv[0]) is an object containing the name the routine was called as (in a C main, that'd be the name the program was invoked as).

In Tcl, though? The array of pointers are not pointers to character strings (although they were in all versions of Tcl before 8.0). ๐Ÿ’…

In the example above, all of the arguments get output with a space between each one, by looping through elements of the objv array from one to the argument count, objc, and a newline is output to terminate the line โ€” it's a simple ``echo'' command, basically. This example uses printf for simplicity. Of course in production code you'd wanna use the Tcl filesystem interfaces. See GetFile(3) and friends for more info. ๐Ÿ“

All arguments from a Tcl call to a Tcl C extension are passed as Tcl Objects. So if your C routine wants to look at one of those arguments as an integer, you need to make a call to a routine to fetch the representation of the object that you need. In the earlier example, for instance, Tcl_GetStringFromObj is called to obtain a textual representation of an object. Additional routines are available to fetch the representation of a data element as other data types:

  • Tcl_GetBooleanFromObj
  • Tcl_GetDoubleFromObj
  • Tcl_GetIntFromObj
  • Tcl_GetLongFromObj
  • Tcl_GetIndexFromObj

...which fetch object representations of Tcl strings as booleans, double-precision floating point, integer, long integer, and lists, among others. ๐Ÿ”ฅ

These routines automatically leave an appropriate error message in the Tcl interpreter's result object and return TCL_ERROR if a conversion error occurs. (For more info on these routines, please look at the Object(3) manpage in the core Tcl distribution.) โญ


๐Ÿ‘‘ RETURNING RESULTS ๐Ÿ‘‘

As you might expect, the API for setting results from C extensions has changed significantly under the object system. The old technique of writing small results directly into the interpreter's result buffer is no longer used, for example. And the notion of having to tell Tcl whether a result is static or dynamic? Also a thing of the past, bestie. Under the object system, results are objects that are set up by your code, and objects are freed when their reference counts say they should be. More on this later. ๐Ÿ’œ

If your program produces a numeric result, it should set the result object to contain that numeric value. A common way of doing this is something like...

    Tcl_Obj *obj;

    obj = Tcl_GetObjResult (interp);
 Tcl_SetIntObj (obj, value);

The above code obtains a pointer to the result object (an object made available to your routine that you're supposed to store your results into) and sets the integer value value into it. ๐ŸŽ€

Another way to do it would be to set up a new object and tell Tcl that this object contains the result...

    Tcl_Obj *resultObj;

    /* create a new object for use as a result */
 resultObj = Tcl_NewObj ();

 Tcl_SetIntObj (obj, value);
 Tcl_SetObjResult (interp, resultObj);

Understanding how results are passed back to Tcl is essential to the C extension writer. Please study the SetObjResult(3) manual page in the Tcl distribution for more information. ๐Ÿ“–


๐Ÿ’… VALIDATING ARGUMENTS ๐Ÿ’…

It's a design goal of Tcl that no Tcl program be able to cause Tcl to dump core. So it's important that extension writers, likewise, use the available methods and tools to make sure their extensions don't allow unchecked input โ€” for example, to cause the code to get some kind of runtime exception. ๐Ÿ˜ญ

The object system has simplified, to some degree, the task of validating arguments, in that the object system automatically attempts type conversions as needed, and will return an error when a type conversion fails. Slay. โœจ

A simple but important check that every C extension should do is verify that it has the right number of arguments.

The act of trying to use, say, a string as an integer, implicitly performs the type conversion of the string and, if it doesn't work as an integer, returns TCL_ERROR. The developer should check for the TCL_ERROR return from all of the GetXxxFromObj commands, and handle them as appropriate. Usually this will mean propagating the error on back to the user, or to an intervening catch, as the case may be.

You should also check that values are in range (when their ranges are known), and so forth. When C data structures need to be handled in Tcl in some form or another, yet the contents of the data must remain opaque to Tcl โ€” as is usually the case with binary data (although future releases of Tcl are expected to have native abilities to read, write and manipulate binary data intrinsically) โ€” handles need to be used. Handles will be described and examples presented, later in this doc. ๐Ÿฆ‹

โœจ ANOTHER C EXTENSION โ€” THE MAX COMMAND โœจ

Okay bestie, next up we're building a whole new command from scratch, and it's lowkey iconic. ๐Ÿ’…

In the command below, two or more arguments get compared against each other, and the one holding the maximum value gets handed back โ€” assuming everything goes according to plan. But heads up: it is an error if there are fewer than two arguments. (And by "two arguments" we mean the pointer to the `max` command text itself, objv[0], plus a pointer to at least one object whose value we're comparing.) ๐Ÿ‘‘

int
Tcl_MaxCmd (clientData, interp, objc, objv)
    char         *clientData;
    Tcl_Interp   *interp;
    int           objc;
    Tcl_Obj     **objv;
{
    int maxVal = MININT;
    int value, idx;

    if (objc < 3)
     return TclX_WrongArgs (interp, objv[0],
                               " num1 num2 [..numN]");

    for (idx = 1; idx < objc; idx++) {
        if (Tcl_GetIntFromObj (interp, objv[idx], &value) != TCL_OK)
            return TCL_ERROR;

        if (value > maxVal) {
            maxVal = value;
        }
    }
 Tcl_SetIntObj (Tcl_GetObjResult (interp), value);
    return TCL_OK;
}

This is where we get to meet the Extended Tcl helper function TclX_WrongArgs. โœจ She's the bestie who handles the extremely common situation of someone calling your command with the wrong number of arguments โ€” she whips up an error message and an error return for you, so you don't have to hand-roll it every single time.

Then Tcl_GetIntFromObj rolls in to fetch the integer values of all the remaining arguments. If any of them fail to convert, we bounce back with a Tcl error. And here's the tea: if an interpreter is specified in the call to Tcl_GetIntFromObj, an appropriate error message about that conversion failure gets left in the result โ€” which is exactly why we pass it along here. ๐Ÿซถ

Once every argument has been examined and we've sniffed out the largest value, we set the result object to contain that value, and we return TCL_OK. Slay. โœจ


๐Ÿ” RETURNING RESULTS ๐Ÿ”

When Tcl-callable functions finish up, they should normally return TCL_OK or TCL_ERROR. TCL_OK means the command succeeded, and TCL_ERROR means the command failed in some abnormal way. You return TCL_ERROR for all syntax errors, for non-numeric values when numeric ones were expected, and honestly just, like, all of that. ๐Ÿ’€

The murkier question โ€” and ngl, it's giving "unclear" โ€” is whether Tcl errors should be returned, or whether a function should just return a status value instead. For example, end-of-file during a gets returns a status, but open returns an error if it fails. Errors can be caught from Tcl programs using the catch command. (Go peek at Tcl's catch(n) and error(n) manual pages. ๐Ÿ“š)

The less common return values are TCL_RETURN, TCL_BREAK and TCL_CONTINUE. These come out to play when you're adding brand-new control and/or looping structures to Tcl. Wanna see them in action? Examine the source code to Extended Tcl's loop commands. Tcl's while, for and if commands used to work in the very same manner, but they're now compiled into bytecode by the bytecode compiler, purely for performance. Glow-up, honestly. โœจ


๐Ÿ”„ ANOTHER C EXTENSION โ€” THE LREVERSE COMMAND ๐Ÿ”„

In the command below, a list gets passed in as an argument, and what comes back is a list containing all of the elements of the list in reverse order. It's an error if anything other than two arguments get passed (the pointer to the `lreverse` command text itself, objv[0], and a pointer to the list we're flipping). ๐Ÿฆ‹

Once lreverse has confirmed it got the correct number of arguments, Tcl_ListObjGetElements is called to crack the list open into its own objc count of elements and objv array of pointers to the list's elements.

Then lreverse operates on that array of pointers, swapping them from lowest to highest, second-lowest to second-highest, and so on down the line. ๐ŸŽ€

Tcl_ListObjAppendElement gets called on successive list elements to build up the new list, which is finally returned as the result of the command.

int
Tcl_LreverseObjCmd(notUsed, interp, objc, objv)
    ClientData    notUsed;        /* Not used. */
    Tcl_Interp   *interp;         /* Current interpreter. */
    int           objc;           /* Number of arguments. */
    Tcl_Obj     **obj;            /* Argument strings. */
{
    int listObjc, lowListIndex, hiListIndex;
    Tcl_Obj **listObjv;
    char *temp, *resultList;
    Tcl_Obj **newListObjv;

    /* Verify argument count.  Since we take only one argument, argument
     * count must be 2 (command plus one argument).
     */
    if (objc != 2)
     return TclX_WrongArgs (interp, objv [0], "list");

    /* Create an object to handle the new list we're creating */
    newListObjv = Tcl_NewObj();

    /* Crack the list at objv[1] into its own count and array of object
     * pointers.
     */
    if (Tcl_ListObjGetElements (interp, objv[1], &listObjc, &listObjv) != TCL_OK) {
     return TCL_ERROR;
    }

    /* For each element in the source list from last to first, append an
     * element to the new list.
     */
    for (listIndex = listObjc - 1; listIndex >= 0; listIndex--) {
     Tcl_ListObjAppendElement (interp, newListObjv, listObjv[listIndex]);
    }
FIX: NEED TO RETURN THE LIST.
    return TCL_OK;
}

๐Ÿ› ๏ธ INSTALLING YOUR COMMAND ๐Ÿ› ๏ธ

To install your command into Tcl you must call Tcl_CreateObjCommand, and you pass it:

  • the pointer to the interpreter you want to install the command into,
  • the name of the command,
  • a pointer to the C function that implements the command,
  • a client data pointer,
  • and a pointer to an optional callback routine.

The client data pointer and the callback routine get described later, don't stress. ๐Ÿซถ

So like, for example, for the max function above (which, incidentally, comes from TclX's tclXmath.c in the TclX7.4/src directory):

Tcl_CreateCommand (interp, "max", Tcl_MaxCmd, (ClientData)NULL,
                  (void (*)())NULL);

In the above example, the max function gets added to the specified interpreter. The client data pointer and callback function pointer are both NULL. (For complete information on Tcl_CreateCommand and its companion routine, Tcl_CommandInfo, please go examine the CrtCommand(3) command page in the core Tcl distribution. ๐Ÿ“–)


๐Ÿงต DYNAMIC STRINGS ๐Ÿงต

Dynamic strings are a super important abstraction that first became available with Tcl 7.0. Dynamic strings โ€” or DStrings โ€” give you a way to build up arbitrarily long strings through a repeated process of appending information to them. DStrings cut down on the amount of allocating and copying required to add info to a string, and on top of that, they make the whole process simpler. It's giving efficiency. โœจ

At first glance it might seem like the object system supersedes DStrings. It does not. Here's why: the performance improvements made possible by the lazy conversion of an object's representation from one datatype to another don't really come into play much while you're constructing strings โ€” because the string representation is always available, either without any type conversion at all, or in cases where type conversion would be necessary anyway, since a string representation of the object is required whenever strings are being constructed by concatenation, etc.

It should be noted, however, that the C level string manipulation capabilities of objects โ€” things like Tcl_AppendToObj and Tcl_AppendStringsToObj โ€” are often plenty enough for whatever you need to do. ๐ŸŒธ

For complete information on dynamic strings, please examine the DString(3) manual page in the core Tcl distribution. For more on Tcl object's string-oriented calls, go seek Tcl_StringObj(3) in the same location.


๐Ÿซ‚ CLIENT DATA ๐Ÿซ‚

The client data pointer gives Tcl commands a way to have data associated with them that isn't global to the C program and isn't baked into the Tcl core either. Client data is essential in a multi-interpreter environment (you know, where a single program has created and is making use of multiple Tcl interpreters), because it's how the C routines maintain whatever permanent data they need on a per-interpreter basis. If your needed static data was just declared static in C, you'll probably run into reentrancy problems when you start working with multiple interpreters. ๐Ÿ˜ญ

Tcl solves this through the client data mechanism. When you're about to call Tcl_CreateObjCommand to add a new command to an interpreter, and your command needs to keep some read/write data across invocations, you should allocate the space โ€” preferably using Tcl_Alloc instead of malloc โ€” and then pass the address of that space as the ClientData pointer to Tcl_CreateObjCommand.

When your command gets called from Tcl, the ClientData pointer you passed to Tcl_CreateObjCommand gets passed right back to your C routine through the ClientData pointer calling argument. Full circle. ๐Ÿ’ซ

Commands that need to share this data with one another can do exactly that by using the same ClientData pointer when the commands get added.

It's important to note that the Tcl extensions in the tclX8.0.0 directory have had all of their data set up in this way. And since release 6.2, Extended Tcl has supported multiple interpreters within one invocation of Tcl. ๐Ÿ‘‘

โœจ THEORY OF HANDLES โœจ

Okay bestie, listen. Sometimes you need a data element that justโ€ฆ cannot be a string in Tcl. Like a pointer to a whole complex C data structure. And the โœจtemptingโœจ thing is to pass pointers around inside Tcl as strings, converting them to and from hex or integer representations.

Do not do this. It is not a good idea. It is too easy to mess one up, and the likely outcome of messing one up is a core dump. ๐Ÿ’€

Instead, we came up with โ€” and heavily use โ€” the concept of handles. A handle is an identifier that a C extension can pass to, and accept from, Tcl. It makes the transition between what your C code knows something as and what name Tcl knows it by as safe and painless as possible. ๐Ÿซถ

Example time, because obviously. The I/O system included in Tcl uses file handles. When you open a file from Tcl, you get back a handle of the form filen, where n is a file number. When you pass that file handle back to puts, gets, seek, flush and so forth, they validate the file handle by checking that the file text is present, then converting the file number to an integer that they use to look into a data structure of pointers to Tcl open file structures. And those structures contain a Unix file descriptor, flags indicating whether or not the file is currently open, whether the file is a file or a pipe, and so forth. ๐ŸŽ€

Handles proved so useful that since TclX release 6.1a, general support has been available to help create and manipulate them. Many of these capabilities have migrated into baseline Tcl. If you have a similar need, you might like to use the handle routines documented in Handles(3) in Extended Tcl. Our recommendation, and we stand by it: use a unique-to-your-package textual handle coupled with a specific identifier, and let the handle management routines validate it when it's passed back. It is much easier to track down a bug when the implicated handle is named something like file4 or bitmap6 than when it's just 6. iykyk. ๐Ÿ•ต๏ธโ€โ™€๏ธ

Also, quick note: Tcl's object system offers another way for complex data structures to exist in parallel with and underneath Tcl strings. As of this writing (May 30, 1997) this is fairly new territory, but things are looking good for the prospects of using the Tcl object system in this manner, and for enhancements to the object system that allow even Tcl objects to have methods in a very straightforward and simple way. ๐Ÿ‘‘


๐ŸŒˆ USING COMMANDS TO DO THE SAME THING, AND MORE ๐ŸŒˆ

There's another handle-like technique, first popularized in the Tk toolkit, and honestly? It eats. It gives you handle-like capabilities plus some neat additional capabilities. ๐Ÿ’…

The move: create a new Tcl command, from C, that uses ClientData to keep a "handle" on its complex underlying data structure. Then, by having that command look at its second argument for what it is to do (its sub-functions), you get these lovely methods โ€” several additional sub-commands that don't pollute the global namespace and only work on (and are available with) the objects (new commands) they are relevant to.

For example, in Tk, creating a checkbutton (checkbutton .b) creates a new Tcl command (.b), that has methods to configure the button, select, deselect, toggle and flash it. Iconic behaviour honestly. โœจ

A lot of people think this is really the way to go, and I am pretty much leaning that way myself. If you use the incr tcl script-level object system for Tcl, objects that you define in Tcl will be highly compatible in terms of their command interfaces and configuration management with objects you create in C using the command-and-ClientData technique described here. I believe Tk has some nice facilities for making this easy for the Tcl programmer. Itcl certainly does. ๐Ÿฆ‹


๐Ÿ” TRACKING MEMORY CORRUPTION PROBLEMS ๐Ÿ”

ngl, this one's the scary section. Occasionally you may write code that scribbles past the end of an allocated piece of memory. ๐Ÿ˜ญ This will usually result in a core dump or a memory allocation failure sometime later in the program โ€” often implicating code that is not actually responsible for the problem, because you start looking from the point where the error is detected, which is usually where the later routine has failed. The way that griefing works is genuinely so unfair. ๐Ÿ’€

The memory debugging routines included in Tcl can help find these problems. Developed by Mark and Karl, the memory debugging routines are now part of baseline Tcl, and are to our knowledge the largest piece of TclX to drop into the core without being reengineered first.

And okay, story time, because it's a good one ๐Ÿ“: summer back in '91, John was sitting in his office in the CS building at UC Berkeley trying to find a memory leak somewhere in Tcl, when he was paid a visit by two long-haired-yet-polite programmers bearing gifts in the form of the technology grab-bag known as Extended Tcl. He saw that, using TclX's malloc routines, Tcl could be prompted to print the filename and line number of every single memory allocation that did not have a corresponding free. It was just what the doctor ordered ;-) See Memory(TCL) for details. ๐Ÿ’–


๐Ÿ“ฆ INSTALLING YOUR EXTENSIONS INTO TCL ๐Ÿ“ฆ

To add your extensions to Tcl, you used to have to statically link them, together with any other extensions, into a single binary executable image. ๐Ÿฅด

Today, although the statically linked executable is still an option, most operating systems โ€” even Microsoft Windows โ€” support shared libraries. And in most cases, Tcl can now make use of those shared libraries such that your extensions, and most others, can now be built as shared libraries that can be loaded in (using package require) by scripts that need them.

Shared libraries can simplify a Tcl installation, because only one copy of Tcl is required, rather than a hodepodge of combinations of applications that you might have found at a big Tcl site in the previous era. No cap, that's a glow-up. โœจ


๐Ÿ› ๏ธ GNU AUTOCONF ๐Ÿ› ๏ธ

While the build procedure for shared libraries varies from system to system, most Unix and Unix workalike systems will figure out the nuances of the compiler and linker arguments automatically when the configure script is run. ๐Ÿ˜Œ

If you are building a package that you plan to make generally available, we strongly recommend that you use GNU autoconf (ftp://prep.ai.mit.edu/pub/gnu) to set up an automatic configure script for it.

Be forewarned: autoconf uses some pretty heavy duty shell and sed script magic to get the job done, and the learning curve can be pretty steep. ๐Ÿซ 

Once done and shaken out, though, it's rewarding to know that your package can build and run on everything from a notebook to a Cray to a RISC SMP server. Main character energy for your build system. ๐Ÿ‘‘


Application-specific startup is accomplished by creating or editing the Tcl_AppInit function. In Tcl_AppInit you should add a call to an application-specific init function which you create. This function should take the address of the interpreter it should install its commands into, and it should install those commands with Tcl_CreateCommand and do any other application-specific startup that is necessary. ๐ŸŽ€

The naming convention for application startup routines is App_Init, where App is the name of your application. So for example, to add an application named cute, one would create a Cute_Init routine that expected a Tcl_Interp pointer as an argument, and add the following code to Tcl_AppInit:

if (Cute_Init (interp) == TCL_ERROR) {
 return TCL_ERROR;
}

As you can guess from the above example, if your init routine is unable to initialize, it should use Tcl_AppendResult to provide some kind of useful error message back to TclX, then return TCL_ERROR to indicate that an error occurred. If the routine executed successfully, it should return TCL_OK. Simple as that bestie. ๐Ÿซถ

When you examine Tcl_AppInit, note that there is one call already there to install an application โ€” the call to TclX_Init installs Extended Tcl into the Tcl core. That one's not yours, it's a gift. ๐ŸŽ


๐Ÿ‘€ MAKING APPLICATION INFORMATION VISIBLE FROM EXTENDED TCL ๐Ÿ‘€

TclX's infox command can return several pieces of information relevant to Extended Tcl, including the application's name, descriptive name, patch level and version. Your application's startup can set these variables to application-specific values. If it doesn't, they are given default values for Extended Tcl. ๐Ÿ™ˆ

To set these values, first be sure that you include either tclExtend.h or tclExtdInt.h from the source file that defines your init routine. This will create external declarations for the variables. Then, set the variables in your init routine, for example:

tclAppName = "cute";
tclAppLongName = "Call Unix/Tcl Environment";
tclAppVersion = "2.1";
Heads up: the default values are set by TclX_Init, so if you wish to override them, you must call your init routine in Tcl_AppInit after its call to TclX_Init. Order matters, bestie, it always does. ๐Ÿ’…

๐ŸŒ™ EXTENDED TCL EXIT ๐ŸŒ™

When Extended Tcl exits, Tcl_DeleteInterp may be called to free memory used by Tcl โ€” normally, this is only called if TCL_MEM_DEBUG was defined, since Unix will return all of the allocated memory back to the system, anyway. If TCL_MEM_DEBUG was defined, it is called so that any memory that was allocated without ever being freed can be detected. This greatly reduces the amount of work to detect and track down memory leaks โ€” a situation where some piece of your code allocates memory repeatedly without ever freeing it, or at least without always freeing it. ๐Ÿ˜ญ

It is often necessary for an application to perform special cleanup functions upon the deletion of an interpreter as well. To facilitate this activity, Tcl provides the ability to perform a function callback when an interpreter is deleted. To arrange for a C function to be called when the interpreter is deleted, call Tcl_CallWhenDeleted from your application initialization routine. For details on how to use this function, read the CallDel(3) manual page that ships with core Tcl. ๐Ÿซก


โœจ EXECUTING TCL CODE FROM YOUR C EXTENSION โœจ

okay so picture this bestie: you're deep in your C extension, vibing, writing C, and then you hit that one operation that would be like two lines in Tcl but absolute agony in raw C ๐Ÿ˜ญ. Fear not!! Tcl hands you a whole suite of C-level interfaces so you can just... make Tcl code run. iconic behavior fr fr.

The old-style calls are:

  • Tcl_Eval
  • Tcl_VarEval
  • Tcl_EvalFile
  • Tcl_GlobalEval

And to get your lil results back out of the interpreter you can reach for Tcl_GetStringResult if you want the string representation of the result, or Tcl_GetObjResult if you want the actual object ๐Ÿ’….

โš ๏ธ Heads up: using interp->result to access the result string has been deprecated. we do not do that anymore, bestie, we've moved on ๐Ÿ’€

Now the Tcl object system came through and added Tcl_EvalObj and Tcl_GlobalEvalObj. The glow-up here? You're evaluating an object, not just a string ๐Ÿฆ‹. And choosing these over the ones above can give you a major performance improvement when your code runs repeatedly (yes, even if it only executes once but loops several times inside itself ๐Ÿ‘€), because these routines let the bytecode compiler compile the code being evaluated and stash the compiled code with the data structure โ€” in an implementation-dependent manner, no cap.

For more tea on this, go consult the EvalObj(3) and Eval(3) manual pages within the Tcl distribution โœจ


๐ŸŒธ ACCESSING TCL VARIABLES AND ARRAYS FROM YOUR C EXTENSIONS ๐ŸŒธ

So besides the non-object-system ways of reading from and storing to Tcl variables โ€” you know, the routines like Tcl_SetVar2 and Tcl_GetVar2 โ€” Tcl variables and arrays can also be read from a C extension as Tcl objects using Tcl_ObjGetVar2, and set from C extensions through Tcl_ObjSetVar2 ๐Ÿซถ

๐Ÿ“Œ please note, bestie: the object versions do not carry forward analogues to the one-variable-name-argument Tcl_GetVar, Tcl_SetVar, and Tcl_UnsetVar.

So if you know you have a scalar, just call the object variable get and set functions with a NULL second argument. But if your variable name might contain an array reference via a self-contained embedded array index (like, I'm asking Tcl_ObjGetVar2 for "foo(5)" instead of "foo" "5"), then add the TCL_PARSE_PART1 flag to the flags in your call ๐Ÿ‘‘

Now โ€” the fact that Tcl_ObjGetVar2 retrieves Tcl objects rather than strings is critical for the object system to be able to provide those performance boosts from "lazy" type conversion and the binary data capabilities. But the arguments containing the variable name โ€” or the array name and element name if they've been split out โ€” also must be specified as Tcl objects rather than strings ๐Ÿ˜ฉ.

While this is useful on occasion, those of us writing C extensions for Tcl in the post-object-system era usually have the names available as plain old char * variables, which means converting the strings to objects before use and accounting for their possible destruction afterwards. annoying, I know.

To simplify the task in those cases, TclX adds the TclX_ObjGetVar2S subroutine ๐Ÿ’– It works just like Tcl_ObjGetVar2, except the one or two variable name arguments are specified as strings, and the routine takes care of making and disposing of object equivalents. chef's kiss, honestly.

Tcl variables can be unset from C via the Tcl_UnsetVar and Tcl_UnsetVar2 functions. There are currently (as of 8.0) no object-system equivalents, so in the rare case where you have the name of the variable you want unset as an object instead of a string, you can call Tcl_GetStringFromObj to obtain the string representation first ๐Ÿ™ˆ

For complete info on these functions, please refer to the ObjSetVar(3) and SetVar(3) manual pages in the doc directory of the core Tcl distribution ๐Ÿ“š


๐ŸŽ€ LINKING TCL VARIABLES TO C VARIABLES ๐ŸŽ€

Tcl_LinkVar and Tcl_UnlinkVar can be used to automatically keep Tcl variables synchronized with corresponding C variables โœจ Once a Tcl variable has been linked to a C variable with Tcl_LinkVar, anytime the Tcl variable is read, the value of the C variable is converted (if necessary) and returned โ€” and when the Tcl variable is written, the C variable will be updated with the new value. it's giving mutual besties ๐Ÿ’ž

Tcl_LinkVar uses variable traces to keep the Tcl variable named by varName in sync with the C variable at the address given by addr.

int, double, boolean and char * variables are supported ๐Ÿ‘‘ You can make your linked variables read only from the Tcl side as well, slay.

๐Ÿšจ WARNING WARNING: the C variables must continually exist while they are linked. In other words, linking "automatic" C variables โ€” those created on the stack while a routine is being executed and destroyed afterwards โ€” will result in a malfunctioning program at best and a coredump or more at worst. do not do this to yourself bestie ๐Ÿ˜ญ

For more info, please examine the LinkVar(3) manual page in the core Tcl distribution ๐ŸŒˆ


๐Ÿงฎ ADDING NEW MATH FUNCTIONS TO TCL ๐Ÿงฎ

As of Tcl version 7.0, math functions such as sin, cos, etc, are directly supported within Tcl expressions โœจ These obsolete the Extended Tcl commands that provided explicit commands for these functions for many, many releases โ€” although procs equivalencing the old TclX commands to the new math functions are still provided for backwards compatibility ๐Ÿซถ

New math functions can be added to Tcl, or existing math functions can be replaced, by calling Tcl_CreateMathFunc.


๐ŸŽฒ ACCESSING AND MANIPULATING THE RANDOM NUMBER GENERATOR ๐ŸŽฒ

Prior to Tcl version 8.0, the Tcl core did not provide access to a random number generator, but TclX did, through its random command ๐Ÿ’… As of Tcl version 8.0, access to a random number generator is provided by baseline Tcl through the new math functions, rand and srand ๐ŸŽฐ

The TclX random command is still available โ€” it has some useful capabilities not directly provided by the new baseline functions ๐Ÿ‘€

For more info on adding your own math functions to Tcl, please study the CrtMathFnc(3) manual page in the core Tcl distribution ๐Ÿ“–


๐Ÿ  CONVERTING FILENAMES TO NATIVE FORM AND PERFORMING TILDE SUBSTITUTIONS ๐Ÿ 

The Tcl_TranslateFileName function is available to C extension writers to translate filenames to a form suitable for use by the local operating system ๐ŸŒ It converts network names to their native form, and if the name starts with a ~ character, the function returns a new string where the name is replaced with the home directory of the given user ๐Ÿกโœจ

For more info please consult the Translate(3) manual page in the core Tcl distribution.


๐ŸŒ€ SETTING THE RECURSION LIMIT ๐ŸŒ€

Tcl has a preset recursion limit that limits the maximum allowable nesting depth of calls within an interpreter. This is useful for detecting infinite recursions before other limits โ€” such as the process memory limit or, worse, available swap space on the system โ€” run out ๐Ÿ˜ต๐Ÿ’ซ

The default limit is just a guess, however, and applications that make heavy use of recursion may need to call Tcl_SetRecursionLimit to raise this limit ๐Ÿ“ˆ

For more info, please consult the SetRecLmt(3) manual page in the core Tcl distribution.


๐Ÿšฆ HANDLING SIGNALS FROM TCL EXTENSIONS ๐Ÿšฆ

okay this one's important, listen up. If an event such as a signal occurs while a Tcl script is being executed, it isn't safe to do much in the signal handling routine โ€” the Tcl environment cannot be safely manipulated at this point because it could be in the middle of some operation, such as updating pointers, leaving the interpreter in an unreliable state ๐Ÿ˜ฌ

The only safe approach is to set a flag indicating that the event occurred, then handle the event later when the interpreter has returned to a safe state, such as after the current Tcl command completes ๐Ÿซก

The Tcl_AsyncCreate, Tcl_AsyncMark, Tcl_AsyncInvoke, and Tcl_AsyncDelete functions provide a safe mechanism for dealing with signals and other asynchronous events โœจ For more info on how to use this capability, please refer to the Async(3) manual page in the core Tcl distribution.

Note that Extended Tcl provides built-in support for managing signals in numerous ways, including:

  • generating them with alarm(2) and kill(2)
  • ignoring them
  • trapping them
  • getting, setting, blocking and unblocking them

You can cause specific code to execute at a safe point after a signal occurs, or cause a Tcl error backtrace on one's occurrence ๐Ÿ’ฅ For more info, please examine the TclX documentation.


๐Ÿช„ PARSING BACKSLASH SEQUENCES ๐Ÿช„

The Tcl_Backslash function is called to parse Tcl backslash sequences. These backslash sequences are the usual sort that you see in the C programming language, such as \n for newline, \r for return, and so forth ๐Ÿ’ซ Tcl_Backslash parses a single backslash sequence and returns a single character corresponding to the backslash sequence.

For more info on this call, look at the Backslash(3) manual page in the core Tcl distribution. And for info on the valid backslash sequences, consult the summary of Tcl language syntax, Tcl(n), in the same distribution ๐Ÿ“š


๐Ÿ—‚๏ธ HASH TABLES ๐Ÿ—‚๏ธ

Hash tables provide Tcl with a high-performance facility for looking up and managing key-value pairs located and maintained in memory โšก Tcl uses hash tables internally to locate:

  • procedure definitions
  • Tcl variables
  • array elements
  • file handles
  • and so forth

And Tcl makes the hash table functions accessible to C extension writers as well ๐Ÿซถ

Hash tables grow automatically to maintain efficiency, rather than exposing the table size to the programmer at allocation time โ€” which would needlessly add complexity to Tcl and would be prone to inefficiency due to the need to guess the number of items that will go into the table, and the seemingly inevitable growth in amount of data processed per run over the useful life of the program ๐Ÿ˜Œ no guessing games here.

For more info on hash tables, please consult the Hash(3) manual page in the core Tcl distribution.


๐Ÿ‘€ TRACING VARIABLE ACCESSES ๐Ÿ‘€

The C extension writer can arrange to have a C routine called whenever a Tcl variable is read, written, or unset ๐Ÿ‘๏ธ๐Ÿ‘๏ธ Variable traces are the mechanism by which Tk toolkit widgets such as radio and checkbuttons, messages and so forth update without Tcl programmer intervention when their data variables are changed โ€” it's literally the main character energy behind reactive widgets ๐Ÿ’… They are also used by the routine that links Tcl and C variables, Tcl_LinkVar, described above ๐Ÿ”—

Tcl_TraceVar is called to establish a variable trace. Entire arrays and individual array elements can be traced as well ๐ŸŽฏ If the programmer already has an array name in one string and a variable name in another, Tcl_TraceVar2 can be called. Calls are also available to request information about traces and to delete them.

For more info on variable traces, consult the TraceVar(3) manual page in the core Tcl distribution โœจ

โœจ TRACING TCL EXECUTION โœจ

okay bestie, Tcl has the ability to call C routines each time it executes a Tcl command, up to a specified depth of nesting levels. The command Tcl_CreateTrace creates an execution trace; Tcl_DeleteTrace deletes it.

Command tracing is used in Extended Tcl to implement the cmdtrace Tcl command, a useful command for debugging Tcl applications.

For complete information on execution tracing, please look at the CrtTrace(3) manual pages in the core Tcl distribution.


๐ŸŒธ EVALUATING TCL EXPRESSIONS FROM C ๐ŸŒธ

Tcl_ExprLong, Tcl_ExprDouble, Tcl_ExprBool, and Tcl_ExprString all take string arguments and, when called, evaluate those strings as Tcl expressions. Depending on the routine called, the result is either a C long, a double, a boolean (int with a value of 0 or 1), or a char * (obtainable through Tcl_GetResult).

To take advantage of the performance gains available through the bytecode compiler, Tcl_ExprLongObj, Tcl_ExprDoubleObj, Tcl_ExprBoolObj, and Tcl_ExprObj all take an object containing an expression to be evaluated (rather than a string.) The result is that bytecode-compiled version of the expression will be kept in the object, alongside the string representation. If the expression is evaluated again, without being changed, it does not have to be recompiled... a major performance win.

For complete information on evaluating Tcl expressions from C, you are invited to examine the ExprLong(3) and ExprLongObj(3) manpages in the core Tcl distribution.


๐Ÿ’… PATTERN MATCHING ๐Ÿ’…

The Tcl_StringMatch function can be called to see if a string matches a specified pattern. Tcl_StringMatch is called by the Tcl string match command, so the format for patterns is identical. The pattern format is similar to the one used by the C-shell; string(n) describes this format.

More information about Tcl_StringMatch is available in the StrMatch(3) manpage in the core Tcl distribution.


๐Ÿ”ฅ REGULAR EXPRESSION PATTERN MATCHING ๐Ÿ”ฅ

Tcl_RegExpMatch can be called to determine whether a string matches a regular expression. Tcl_RegExpMatch is used internally by the regexp Tcl command.

As regular expressions are typically "compiled" before use, a fairly involved process, Tcl also supports routines that separate the compilation of an expression from its use: Tcl_RegExpCompile, Tcl_RegExpExec, and Tcl_RegExpRange. If an expression is going to be matched many times, doing the compile once and caching the compiled regular expression result, then reusing the cached version by using Tcl_RegExpExec, can be a significant performance win.

For more information on this function, please consult the RegExp(3) manpage in the core Tcl distribution.


๐Ÿ‘‘ MANIPULATING TCL LISTS FROM C EXTENSIONS ๐Ÿ‘‘

The C extension writer often needs to create, manipulate and decompose Tcl lists. Tcl_SplitList and Tcl_Merge used to be the only way to parse strings into lists and vice versa. As of Tcl 8, lists can be parsed and assembled, object-style, using Tcl_ListObjGetElements and Tcl_SetListObj, and friends. Once again the "win" of using object-system-based list manipulation, instead of the previous string based routines, is that the parsing of a string in an object to a list is cached in the object structure, the same as with integers and floating point numbers, compiled procedures, etc. The next time this string needs to be looked at as a list, if the contents of the string have not changed, the string does not have to be parsed.

In the author's experience, working with an admittedly degenerate test whereby we iterated rather inefficiently across a 6,000-element list, a speedup factor of more than 2500 was obtained over the previous non-object-based version of Tcl.

For more information on these commands, please consult the ListObj(3) manual page in the core Tcl distribution.


๐ŸŽ€ CONCATENATING STRINGS ๐ŸŽ€

Tcl_ConcatObj concatenates the string representation of zero or more objects into a single new object. The elements of the new string are space-separated. Tcl_Concat does the same thing for strings, as Tcl_ConcatObj does for objects.

Concatenating strings is similar to constructing lists from them, except that Tcl_ConcatObj and Tcl_Concat do not attempt to make the resulting string into a valid Tcl list.

Tcl_Concat is documented in the Concat(3) manpage, and Tcl_ConcatObj in the tringObj manpage, both in the core Tcl distribution.


๐Ÿฆ‹ DETECTING WHETHER OR NOT YOU HAVE A COMPLETE COMMAND ๐Ÿฆ‹

C routines that collect data to form a command to be passed to Tcl_Eval often need a way to tell whether they have a complete command already or whether they need more data. (Programs that read typed-in Tcl input such as Tcl shells need this capability, for instance.) Tcl_CommandComplete can be used to tell whether or not you have a complete command.

For more information examine CmdCmplt(3) in the core Tcl distribution.


๐ŸŒˆ RECORDING COMMANDS FOR COMMAND HISTORY ๐ŸŒˆ

Tcl has a history mechanism that is accessed from Tcl through the history command. If you want your extension to propagate commands into the command history, you should call Tcl_RecordAndEvalObj (object system) or Tcl_RecordAndEval (old system),

These commands work like Tcl_EvalObj and Tcl_Eval, respectively, except that these versions record the command as well as executing it.

Tcl_RecordAndEval and Tcl_RecordAndEvlObj should only be called with user-entered top-level commands, since the history mechanism exists to allow the user to easily access, edit and reissue previously issued commands.

For complete information on these functions, please examine the RecordEval.3 and RecEvalObj.3 manual pages in the core Tcl distribution.


๐Ÿ’œ CONVERTING FLOATING POINT VALUES TO STRINGS ๐Ÿ’œ

The Tcl object system's Tcl_GetDoubleFromObj and Tcl_SetDoubleObj use Tcl objects, rather than the strings used by Tcl_PrintDouble, and convert, when necessary, an ASCII string to a double and back again.

These routines ensure that the string output will continue to be interpretable as a floating point number, rather than an integer, by always putting a .'' or e'' into the string representing the number.

The precision of the output string is controlled by the Tcl tcl_precision variable.

For complete information on these routines, please examine DoubleObj(3) and PrintDbl(3) in the core Tcl distribution.


๐Ÿ“ CREATING CHILD PROCESSES AND PIPELINES FROM C ๐Ÿ“

Tcl_OpenCommandChannel provides a C-level interface to the exec and open commands. The child (or pipeline of children) can have its standard input, output and error redirected from files, variables or pipes. To understand the meaning of the redirection symbols understood by this function, look at the exec(n) Tcl command. For complete information on Tcl_OpenCommandChannel, please examine OpenFileChnl(3).


๐Ÿงš ACCESSING TCL FILEHANDLES FROM C ๐Ÿงš

On Posix/Unix systems, Tcl filehandles passed to your C extension can be translated to a Posix FILE * structure using the Tcl_GetOpenFile function, documented in GetOpnFl.3.


๐Ÿ’€ MANAGING BACKGROUND PROCESS TERMINATION AND CLEANUP ๐Ÿ’€

When a Posix system does a fork to create a new process, the process ID of the child is returned to the caller. After the child process exits, its process table entry (and some other data associated with the process) cannot be reclaimed by the operating system until a call to waitpid, or one of a couple of other, similar system calls, has been made by the parent process.

The C extension writer who has created a subprocess, by whatever mechanism, can turn over responsibility for detecting the processes' termination and calling waitpid to obtain its exit status, by calling Tcl_DetachPids on it.

Tcl_ReapDetachedProcs is the C routine that will detect the termination of any processes turned over to Tcl, permitting the processes to be fully reclaimed by the operating system. It is usually not necessary to call Tcl_ReapDetachedProcs, as it is called automatically every time exec is performed.

For complete information on these routines, please look at DetachPids(3) in the core Tcl distribution.


โญ FOR MORE INFORMATION โญ

In addition to the documentation referenced above, you can learn a lot by studying the source code of the commands added by Tcl, Tk and Extended Tcl, etc. The comp.lang.tcl Usenet newsgroup is read by hundreds of thousands of Tcl people. A number of Frequently Asked Questions (FAQs) about Tcl are posted there periodically. The newsgroup is a good place to ask questions (after you've made sure they're not already answered in the FAQ ;-)

Finally, if you have interactive Internet access, you can ftp to ftp://ftp.neosoft.com/pub/tcl, the site for contributed Tcl sources. This site contains quite a few extensions, applications, and so forth, including several object-oriented extension packages.

If you have access via the world-wide web, check out the Sun Microsystems site (http://sunscript.sun.com), the contributed sources archive website (http://www.neosoft.com/tcl), and the homepage for Extended Tcl (http://www.neosoft.com/tclx).


๐Ÿ’– AUTHORS ๐Ÿ’–

Extended Tcl was created by Karl Lehenbauer (karl@neosoft.com) and Mark Diekhans (markd@grizzly.com).


okay bestie, that's the whole page. source/version is Tcl, the manual page is Command Writing(3tclx), and the date? this footer didn't hand me one, so I'm not inventing one โ€” no cap. periodt. ๐Ÿ’…โœจ

๐Ÿ“ฆ where this page comes from