Hacker News new | ask | show | jobs
by acqq 4684 days ago
I'd prefer such code to actually be the part of compiler, simply, C headers directly readable by the compiler as soon as they are referenced from the code as C headers.
3 comments

That should be possible to perform automatically for simple libraries once bindgen is officially in the compiler (again, there are long-term plans for this sort of automatic binding step). But bindgen can't do everything: if you have C functions defined as macros (which so many C libs seems to do, extensively) then you're SOL and will end up needing to implement those functions manually anyway.
This is roughly what cgo does, but cgo AFAIK (at least, in 1.0.3 in earlier) does not fully comprehend C preprocessor macros, which are used all over the place in some libraries to define both functions and structs, largely for compatibility reasons. Taking a random example, OpenSSL's EVP_CIPHER_CTX_block_size is a macro that simply returns an internal struct field; to call it from Go, it needs to be explicitly wrapped into a C function. I presume this is because cgo can't infer the signature.

For other things, like some of the constants ncurses defines, it's much less clear what's going on (specifically, I had a hard time with any macro defined with the NCURSES_ACS macro, though that was pre-Go1 -- I believe cgo can now use these macros directly).

There's an additional impedance mismatch when the C headers use macros for conditional compilation (for, e.g., cipher suites that can be optionally compiled out), but it's not a worry if you either are conservative with the functionality you use, or control the packages installed on a system.

I haven't had a chance to play with Rust yet, but since it uses C linkage directly for it's FFI layer, I suspect these problems are less easily addressable.

The only way to do this fully automatic is to integrate a partial C compiler, able to understand the pre-processor and all types of declarations.
There was/is a plan to use clang to help with this.

(In fact, rustc used to build clang as well as LLVM, but this was disabled since it wasn't being used (yet).)

This is the approach also taken by DStep for D.

https://github.com/jacob-carlborg/dstep