Hello,

The rule of thumb is too never confuse and avoid mixing:

  * untraced pointers (ptr T)
  * traced pointers (ref T)
  * stack objects



If you want to store the address of a stack object, you are screwed immediatly 
when the function where your object is defined returns. So you have to copy it.

If you want to store the address (I mean casting the ref to a pointer) of a 
traced object (ref), it is exactly the same problem: the nim GC (ARC) will 
detect when your object is no longer referenced and dealloc it (for example 
when your function returns !). It is possible to tell the GC to not do that 
with GC_ref and GC_unref, but this is not a really good practice.

Your best bet is either :

  * to create and store your objects as ref (no conversion to pointers)
  * to use directly pointers and manage memory yourself (with all the risks it 
implies). We generally use that kind of idiom : cast[ptr 
MyObject](https://forum.nim-lang.org/alloc0\(sizeof MyObject\))



And I you want to share your data with C functions, it depends on what C will 
do, if C will store the pointer, it is unsafe to pass a ref object or the 
adress of a stack object.

Reply via email to