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:
proc printf(formatstr: cstring) {.importc: "printf", varargs,
header: "<stdio.h>".}
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:
var str: string = "Hello!"
var cstr: cstring = str
var newstr: string = $cstr
cstring literals shouldn’t be modified.
var x = cstring"literals"
x[1] = 'A' # This is wrong!!!
If the cstring originates from a regular memory (not read-only memory), it can be modified:
var x = "123456"
var s: cstring = x
s[0] = 'u' # This is ok
cstring values may also be used in case statements like strings.