I'm working on wrapping 7z's C implementation - https://github.com/kornelski/7z/blob/master/C - and trying to figure out how to access an array of bytes populated by the underlying code.
type
Byte = cuchar
var carrrayptr: ptr Byte
How do I access the nth byte in that string of bytes?
The length of bytes is unknown at compile time so I cannot cast to an array of fixed length.
let carray = cast[ptr array[len, Byte]](str)
echo carray[i]
Thanks in advance.
Usually you would use a pointer to an unchecked array, like ptr UncheckedArray[Byte] (documentation here).
I am curious though - how are you able to know what the bounds of the array are at runtime?
Since you are writing a wrapper to a C library, have you checked out c2nim and Nimgen? They generally make wrapping a C library much easier - usually all you need to do is tweak the types a bit afterwords, and add a high-level interface for safety.
Yes, I'm using nimgen, was just struggling with translating this line in 7zMain.c which digs through the nth byte of an internal array.
At runtime, I am looping over db.NumFiles so stay within limit. Got it working thanks to your tip to use UncheckedArray and the following sample in Arraymancer.
For anyone else who wants to access a C pointer array in Nim like a regular Nim array:
char *n = malloc, etc.
var n which maps to c array
let an = cast[ptr UncheckedArray[char]](n)
echo an[x]
Thanks a bunch!