The code following is fine in the prevous version, but it failed with the current devel branch because access the terminator zero is disabled.

var a = ""
let b = addr a[0]

Now, there is any way I can get the address of the empty string?

2018-05-08 10:57:57
Maybe the question should be elevated to why would you need this? Now that the distinction between empty strings and nil strings is gradually erased, your use case could become a bigger problem. 2018-05-08 11:07:28

I'm not sure, but here b should contain ptr to empty string - am I right?

var a = ""
let b = a.cstring
echo $cast[int](b)

But why do you need this?

2018-05-08 11:22:29

@c0ntribut0r

Thank you, this is the method I use now.

Because I need to call c function, so I need the address of the string.

2018-05-08 11:25:19

If you're using FFI and the proc accepts cstring type, you don't even need to convert string to cstring at all:

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

2018-05-08 11:41:24
I need to get the pointer, then set the pointer to a struct. So I cannot just use FFI. 2018-05-09 12:41:05

This is shorter and a bit more clean in my opinion

var a: cstring = ""
let a_ptr = cast[ByteAddress](a)

echo a_ptr

2018-05-09 14:02:46

@slangmgh Did I understand? Are you setting a char * in a struct?

FYI, this is very memory unsafe. I'm not sure how long your struct will live, but if the C implementation expects a heap allocated string or static char array then you can have problems.

The Nim GC can't automatically track references in the C code, so your string could be deleted while still in use! To fix this, you can manually control the string's reference count.

Have a look here. Hope that helps!

2018-05-11 00:47:19
It just parameter, useless after call. 2018-05-11 06:20:34

var a = ""

With a[0] you expect to get the null terminator. Neither in old nor in new Nim you are allowed to write to it. With addr a[0] you get the address of a null terminator that you are not allowed to write to. You just should not do that. Btw addr a is possible though. But it is probably a better way to pass the string as a var parameter.

2018-05-15 10:19:11
<<<••12••>>>