Very useful templates for anyone interfacing with C. Thank you very much.

Since I usually do a lot of pointer work in a given file, I switched to this: 
    
    
    template usePtr*[T]() =
      template `+`(p: ptr T, off: Natural): ptr T =
        cast[ptr type(p[])](cast[ByteAddress](p) +% int(off) * sizeof(p[]))
      
      template `+=`(p: ptr T, off: Natural) =
        p = p + off
      
      template `-`(p: ptr T, off: Natural): ptr T =
        cast[ptr type(p[])](cast[ByteAddress](p) -% int(off) * sizeof(p[]))
      
      template `-=`(p: ptr T, off: Natural) =
        p = p - int(off)
      
      template `[]`(p: ptr T, off: Natural): T =
        (p + int(off))[]
      
      template `[]=`(p: ptr T, off: Natural, val: T) =
        (p + off)[] = val
    
    ...
    usePtr[my_type]()
    

Note the use of `Natural`. C coders often use unsigned for bit manipulations or 
array indices, and **c2nim** converts those to `cuint`, which do not work for 
array look-ups.

Actually, I wonder why `uint` is not used for **Nim** bit manipulators. 
"Signed" operations are confusing. Do you know the reason? (`ByteAddress` is 
`int` now, btw. 
[https://nim-lang.org/docs/system.html#ByteAddress](https://nim-lang.org/docs/system.html#ByteAddress)
 )

Reply via email to