Pony supports integration with other native languages through the Foreign Function Interface (FFI). The FFI library provides a stable and portable API and high-level programming interface allowing Pony to integrate with native libraries easily.
Note that calling C (or other low-level languages) is inherently dangerous. C code fundamentally has access to all memory in the process and can change any of it, either deliberately or due to bugs. This is one of the language’s most useful, but also most dangerous, features. Calling well written, bug-free, C code will have no ill effects on your program. However, calling buggy or malicious C code or calling C incorrectly can cause your Pony program to go wrong, including corrupting data and crashing. Consequently, all of the Pony guarantees regarding not crashing, memory safety and concurrent correctness can be voided by calling FFI functions.
FFI is built into Pony and native libraries may be directly referenced in Pony code. There is no need to code or configure bindings, wrappers or interfaces.
Here’s an example of an FFI call in Pony from the standard library. It looks like a normal method call, with just a few differences:
@fwrite[U64](data.cstring(), U64(1), data.size(), _handle) The main difference is the @ symbol before the function name. This is what tells us it’s an FFI call.
If Pony code calls FFI functions, then those functions, or rather the libraries containing them, must be linked into the Pony program.
Use for external libraries To link an external library to Pony code another variant of the use command is used. The “lib” specifier is used to tell the compiler you want to link to a library. For example:
use "lib:foo" As with other use commands a condition may be specified.
The FFI support in Pony uses the C application binary interface (ABI) to interface with native code. The C ABI is a calling convention, one of many, that allow objects from different programming languages to be used together.
Writing a C library for Pony Writing your own C library for use by Pony is almost as easy as using existing libraries.
Let’s look at a complete example of a C function we may wish to provide to Pony.
Some C APIs let the programmer specify functions that should be called to do pieces of work. For example, the SQLite API has a function called sqlite3_exec that executes an SQL statement and calls a function given by the programmer on each row returned by that statement. The functions that are supplied by the programmer are known as “callback functions”. Some specific Pony functions can be passed as callback functions.