tonetheman's blog

using nim to make a system call

Fairly cool that you can make system calls with nim. Just saving it here.

The coloring below is a little wonky maybe bearblog does not know nim syntax.

# had to read the header file to make this
type utsname {. importc: "struct utsname" header: "sys/utsname.h" .} = object
    sysname : array[65,char]
    nodename : array[65,char]
    release : array[65,char]
    version : array[65,char]
    machine : array[65, char]
    domainname : array[65, char]

proc uname(buf:pointer): cint {. importc: "uname", header: "sys/utsname.h" .}

# slower and clearer way
proc make_string_from_array(buf : array[65,char]) : string =
    var sbuf = newString(65)
    for i in countup(0,65-1):
        sbuf[i] = buf[i]
    return sbuf

# shorter way prob implemented like my slower way?
proc ms(buf : array[65,char]) : string =
    result = newString(65)
    copyMem(result[0].addr, buf[0].unsafeAddr, buf.len)

var u : utsname
var ret = uname( addr u)
echo("ret : ",ret)
echo("sysname : ", ms(u.sysname))
echo("nodename : ", ms(u.nodename))
echo("release: " , ms(u.release))
echo("version : ",ms(u.version))
echo("machine: ",ms(u.machine))
echo("domain: ",ms(u.domainname))

Updated: made a better way to turn a char array into a string