Updated 2014-01-29 13:30:02 by oehhar

The DString (formally, a Tcl_DString) is a data type defined in the Tcl C library. It is similar to a C string, but it can dynamically (hence the D) grow to be as large as it needs to be. Using DStrings thus avoids a lot of risks for buffer overflow that plague many "ordinary" C programs.

[Guess by a newcomer: DStrings used to be the main workhorses in Tcl before the introduction of Tcl_Objs, and thus have a bunch of features for constructing DStrings with list structure. These features are not so interesting now, but DStrings remain useful for constructing complex strings of other sorts (e.g., error messages).]

DKF: They're good for things like temporary buffers, and are used in quite a lot of places in the Tcl core still. The list-related stuff is rare though; that's usually done with Tcl_Obj-based list routines nowadays.

Initialization edit

There are two ways:
 /* either this: */
 Tcl_DString *dsPtr;
 Tcl_DStringInit(dsPtr);

 /* or this: */
 Tcl_DString dsStrng;
 Tcl_DStringInit(&dsStrng);

Which is the preferred way and why. The Tcl sources use both forms.

Lars H: The difference between these is in where the Tcl_DString structure itself gets allocated, is it not? The second places it on the stack (additional heap space will be allocated if the string outgrows this struct), the first places it just about anywhere. This is nothing particular to DStrings. Note that going just
 {
    Tcl_DString *dsPtr;
    Tcl_DStringInit(dsPtr);
    ...
 }

is an error — Tcl_DStringInit is operating on memory pointed at by the uninitialised pointer dsPtr.

  Is a DString in TCL UTF 8 format ?

HaO 2014-01-29: The DString data may be of any type and need not be in the TCL UTF8 format. It is a bit like dynamical malloc. The length is always in bytes and not in UTF characters.

Nevertheless, the following functions will require or return TCL UTF8 format:

  • [Tcl_DStringResult]
  • [Tcl_DStringGetResult]
  • [Tcl_ExternalToUtfDString]

And the following will explicitly not return TCL UTF8 format:

  • [Tcl_UtfToExternalDString]