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?
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?
@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.
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")
This is shorter and a bit more clean in my opinion
var a: cstring = ""
let a_ptr = cast[ByteAddress](a)
echo a_ptr
@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!
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.
Here is the code from asyncpg package in apg_core.nim, it works before and doesn't now:
# cast[<v>](addr <n>[0])
proc castPointer0(n: NimNode, v: string): NimNode {.compileTime.} =
result = newNimNode(nnkCast).add(
newIdentNode(v),
newNimNode(nnkCommand).add(
newIdentNode("addr"),
newNimNode(nnkBracketExpr).add(n, newLit(0))
)
)
I don't know how castPointer0 is used. But my experience tells me it should never have been used in the first place. You can only take the address of the first element of a string when the string is not empty.
Create an issue in the issue tracker. https://github.com/cheatfate/asyncpg/issues