81 points · by j-james · 5y ago · 22 comments
proc csetvbuf(f: File,
buf: pointer,
mode: cint,
size: csize):
cint {.importc: "setvbuf",
header: "stdio.h".}
# ...intervening code...
discard csetvbuf(stdout, nil,
0, 16384)
c2nim is more helpful for larger C APIs with a lot of C structs and a wide set of entrypoints/API calls. For simple enough C code it can be used as a "starting point" to port the whole thing, but you will probably at least want to change things like a1, a2, etc. parameter names ("a" for "argument"). Nim has named arguments (like Python, f(x=2)) so such names are a bit more important. (Not that all code meant to be read by a human should not have good param names.)As long as extensions are careful to stay "syntactically isolated", the complexity of parsing C need not explode. E.g., at least on Linux where glibc headers are very gcc-tilted, the only extension tcc really needs is that __attribute__(()) stuff (maybe 1 or 2 other "just ignore this stuff" things).
While there can always be edge cases that are broken, I use tcc daily on Linux without issue. So, I would encourage people to not view C as an untamable complexity monster or be captive to prevailing implementations. { C++ is, of course, a more unfortunate story in this and so many other regards :-) }
But if you wanted to port C to a "pure Nim" for whatever reasons (e.g. to also work at compile-time in the Nim VM or the Javascript backend) c2nim also works and can help. It may not work so well on fancier code, e.g. using a lot of cpp macros, etc. That tends to turn up more in .c files than .h files, but the boundary is obviously somewhat arbitrary.