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 to 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. However in practice this almost never happens as the GC considers stack roots conservatively. One can use the builtin procs GC_ref and GC_unref to keep the string data alive for the rare cases where it does not work.

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