cstring type

The cstring type meaning compatible string is the native representation of a string for the compilation backend. For the C backend the cstring type represents a pointer to a zero-terminated char array compatible with the type char* in ANSI C. Its primary purpose lies in easy interfacing with C. The index operation s[i] means the i-th char of s; however no bounds checking for cstring is performed making the index operation unsafe.

A Nim string is implicitly convertible to cstring for convenience. If a Nim string is passed to a C-style variadic proc, it is implicitly converted to cstring too:

  1. proc printf(formatstr: cstring) {.importc: "printf", varargs,
  2. header: "<stdio.h>".}
  3. printf("This works %s", "as expected")

Even though the conversion is implicit, it is not safe: The garbage collector does not consider a cstring to be a root and may collect the underlying memory. For this reason, the implicit conversion will be removed in future releases of the Nim compiler. Certain idioms like conversion of a const string to cstring are safe and will remain to be allowed.

A $ proc is defined for cstrings that returns a string. Thus, to get a nim string from a cstring:

  1. var str: string = "Hello!"
  2. var cstr: cstring = str
  3. var newstr: string = $cstr

cstring literals shouldn’t be modified.

  1. var x = cstring"literals"
  2. x[1] = 'A' # This is wrong!!!

If the cstring originates from a regular memory (not read-only memory), it can be modified:

  1. var x = "123456"
  2. var s: cstring = x
  3. s[0] = 'u' # This is ok

cstring values may also be used in case statements like strings.