4 ms·
Most languages can call C libraries because they can call any libraries, not because C libraries are language agnostic.
by GoblinSlayer 5y ago
Most languages can call C libraries because they can call any libraries, not because C libraries are language agnostic.
- couchand 5y agoThat doesn't ring true to me. My FFI experience is somewhat limited (JS to C, JS to C++ via C wrappers, Rust to C, Rust to C++ via C wrappers) but from what I've seen you have to speak C to make FFI.
- GoblinSlayer 5y agoFew languages truly speak full C (e.g. through clang plugin), they support ABI, but there are libraries like libpng and gtk with API disconnected from ABI, for them FFI doesn't resemble heavily macro encumbered C API.
- matheusmoreira 5y agoHigher level languages such as C++ have extremely complex binary interfaces. Only C++ code dares to link against C++ code. Even then there are problems between different compilers and even different versions of the same compiler. New standard version comes out, it requires that standard classes have certain performance characteristics... Suddenly compilers are breaking binary compatibility in order to restablish conformance. So in order to have usable libraries people will wrap their C++ implementation in C interfaces. Rust faces the same problem. All those nice abstractions result in a complex ABI that will never touched by anything outside the Rust ecosystem. There is no escaping the extern "C". Some languages are virtualized. Java, C#, Ruby, Python, Javascript all have virtual machines. There's no way to interface directly with code running in those languages. We must interface with the virtual machine instead: import it into our process and ask it to call the functions we want to use. C binary interfaces are not language agnostic but they are quite simple. The result of compiling a C library is symbols pointing to functions with simple calling conventions. As a result, virtually any language can look up these symbols and call them.
- GoblinSlayer 5y agoAn example of a relatively simple non-C interface is the linux kernel interface. It's so non-C you can't even cleanly interface with it from C.
- matheusmoreira 5y agoYes. The Linux system call calling convention doesn't match the C ones at all. One needs inline assembly in order to interface with the Linux kernel from C. The ideal solution is to have a system_call keyword built into the compiler that emits the proper instructions for the target platform.