Skip to content

Calling C from Pony

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.

Safely does it

It is VERY important that when calling FFI functions you MUST get the parameter and return types right. The compiler has no way to know what the native code expects and will just believe whatever you do. Errors here can cause invalid data to be passed to the FFI function or returned to Pony, which can lead to program crashes.

To help avoid bugs, Pony requires you to specify the type signatures of FFI functions in advance. While the compiler will trust that you specify the correct types in the signature, it will check the arguments you provide at each FFI call site against the declared signature. This means that you must get the types right only once, in the declaration. A declaration won’t help you if the argument types the native code expects are different to what you think they are, but it will protect you against trivial mistakes and simple typos.

Let’s create a directory named pony-example. On Windows, the C function _mkdir takes just the path. On Linux, mkdir also takes a file mode. We can give each function its own declaration and select the one we need when we compile the program.

use @_mkdir[I32](path: Pointer[U8] tag) if windows
use @mkdir[I32](path: Pointer[U8] tag, mode: U32) if linux

actor Main
  new create(env: Env) =>
    let path = "pony-example"
    let result = ifdef windows then
      @_mkdir(path.cstring())
    elseif linux then
      @mkdir(path.cstring(), 0x1C0)
    else
      compile_error "This example supports Windows and Linux"
    end
    if result == 0 then
      env.out.print("Created " + path)
    else
      env.err.print("Couldn't create " + path)
      env.exitcode(1)
    end

The @ before a function name marks an FFI call. The matching use @ declaration gives the return type in square brackets, followed by the parameters in parentheses. A use @ declaration can take a condition just like other use declarations. On Linux, the compiler selects the declaration with if linux and the call with two arguments. The mode 0x1C0 requests read, write, and execute permission for the owner. On either platform, a return value of zero means the directory was created. If you run the program a second time, the directory already exists and the call fails.

If the name of the C function that you want to call is also a reserved keyword in Pony (such as box), you will need to wrap the name in double quotes (@"box"). If you forget to do so, your program will not compile.

An FFI signature is public to all Pony files inside the same module, so you only need to write them once.

C types

Many C functions require types that don’t have an exact equivalent in Pony. A variety of features is provided for these.

For FFI functions that have no return value (i.e. they return void in C) the return value specified should be None.

In Pony, a String is an object with a header and fields, while in C a char* is simply a pointer to character data. The .cstring() function on String provides us with a valid pointer to hand to C. Our mkdir example above makes use of this for the first argument.

Pony normally passes classes and structs to C by pointer. A Pony class has a type descriptor before its fields. To match the layout of a C struct, use a Pony struct with matching field types in the same order.

For a C pointer to a simple type, you can use Pony’s Pointer with the element type as its type argument. For instance, Pointer[U8] tag can hold the address of a byte. What if the C function accepts a pointer to any type? C’s memcpy takes two such pointers, declared as void* and const void*, and copies a given number of bytes from one to the other.

use @memcpy[Pointer[U8]](
  dst: Pointer[None] tag, src: Pointer[None] tag, n: USize)

actor Main
  new create(env: Env) =>
    let source = "Hello"
    let copy = recover iso Array[U8].init(0, source.size()) end
    @memcpy(copy.cpointer(), source.cpointer(), source.size())
    env.out.print(String.from_iso_array(consume copy))

Declaring the parameters as Pointer[None] tag lets us pass pointers with any element type. Here, both pointers refer to bytes. We make a separate array with one element for every byte in source, so the whole string fits. After the copy, we turn the array into a string and print Hello. The C return type is void* because memcpy returns the destination pointer it received. Since our destination holds bytes, we can declare that return type as Pointer[U8].

Sometimes C needs the address of a Pony variable. The C function frexp splits a number into a fraction and a power of two. It returns the fraction and writes the exponent into a signed int supplied by the caller.

use @frexp[F64](value: F64, exponent: Pointer[I32])

actor Main
  new create(env: Env) =>
    var exponent: I32 = 0
    let fraction = @frexp(0.125, addressof exponent)
    env.out.print(fraction.string() + " * 2^" + exponent.string())

We use addressof exponent to pass the address of our I32 variable. When frexp returns, exponent holds the value C wrote there. The program prints 0.5 * 2^-2, which is another way to write 0.125.

Get and Pass Pointers to FFI

Some C libraries give you a pointer that you only ever pass back to the library. You can use such a pointer without knowing what the data at that address looks like. On a system with the X11 and EGL development libraries and an X11 display, for example, you can open an X display and use it to get an EGL display.

use "lib:X11"
use "lib:EGL"

use @XOpenDisplay[Pointer[_XDisplay]](name: Pointer[U8] tag)
use @eglGetDisplay[Pointer[_EGLDisplay]](display: Pointer[_XDisplay] tag)
use @XCloseDisplay[I32](display: Pointer[_XDisplay] tag)

primitive _XDisplay
primitive _EGLDisplay

actor Main
  new create(env: Env) =>
    let x_display = @XOpenDisplay(Pointer[U8])
    if x_display.is_null() then
      env.err.print("Couldn't open the X display")
      env.exitcode(1)
      return
    end

    let egl_display = @eglGetDisplay(x_display)
    if egl_display.is_null() then
      env.err.print("Couldn't get an EGL display")
      env.exitcode(1)
    else
      env.out.print("Got an EGL display")
    end
    @XCloseDisplay(x_display)

The two use "lib:..." directives link the libraries that provide these functions. Passing a null pointer to XOpenDisplay selects the default X display. If the call succeeds, we pass the returned pointer to eglGetDisplay, then close the X display after checking the result. Why declare a different primitive for each kind of display? Try passing egl_display to XCloseDisplay. The compiler rejects the call because XCloseDisplay expects a Pointer[_XDisplay] tag. We use the two primitives only as type arguments to Pointer.

Working with Structs: from Pony to C

On Linux, writev writes data from one or more buffers to a file descriptor. For each buffer you give it a struct iovec, which holds the address of the first byte and the number of bytes to write. Here are the C types we need:

struct iovec {
  void *iov_base;
  size_t iov_len;
};

ssize_t writev(int fd, const struct iovec *iov, int iovcnt);

To write a string to standard output, we need just one buffer. We can define a Pony struct with the same field types in the same order and pass it directly to @writev:

use @writev[ISize](fd: I32, iov: IOVec tag, iovcnt: I32)

struct IOVec
  let base: Pointer[U8] tag
  let len: USize

  new create(data: String) =>
    base = data.cpointer()
    len = data.size()

actor Main
  new create(env: Env) =>
    let data = "Hello from Pony!\n"
    if @writev(1, IOVec(data), 1) != data.size().isize() then
      env.err.print("Couldn't write the whole message")
      env.exitcode(1)
    end

The first 1 is the file descriptor for standard output. IOVec(data) supplies a pointer to our struct, and the final 1 tells C how many structs it can read there. On success you’ll see Hello from Pony!. The return type is signed because writev can return either the number of bytes written or -1 for an error.

You can also describe the same fields with a tuple. This time you need addressof to pass a pointer to the tuple:

use @writev[ISize](fd: I32, iov: Pointer[IOVec] tag, iovcnt: I32)

type IOVec is (Pointer[U8] tag, USize)

actor Main
  new create(env: Env) =>
    let data = "Hello from Pony!\n"
    var iov: IOVec = (data.cpointer(), data.size())
    if @writev(1, addressof iov, 1) != data.size().isize() then
      env.err.print("Couldn't write the whole message")
      env.exitcode(1)
    end

Passing structs by value

Suppose a C library defines a point with two fields, double x and double y. Its point_sum function takes a copy of the point and adds the coordinates. How do you pass that copy when a Pony struct normally supplies a pointer? Mark the parameter with \by_value\:

// In C: double point_sum(struct Point p)
use @point_sum[F64](p: Point \by_value\)

struct Point
  var x: F64 = 0
  var y: F64 = 0

actor Main
  new create(env: Env) =>
    let p: Point = Point
    p.x = 3
    p.y = 4
    let sum = @point_sum(p)
    env.out.print("sum: " + sum.string())

You still pass p at the call site. The compiler generates a wrapper that reads the struct through the pointer and passes its value to C. Annotate each struct parameter that C takes by value.

A struct passed this way must have at least one field. The fields must be C-compatible primitives or pointers. The compiler doesn’t support nested embedded structs, 128-bit integer fields, or \by_value\ on functions that take a variable number of arguments. For these cases you can write a C shim.

Working with Structs: from C to Pony

C functions can also write into a struct you provide. For example, on x86-64 Linux with glibc, you can call ioctl with the request code 0x5413 (TIOCGWINSZ) to read the terminal size. Run this program with a terminal as standard input:

use @ioctl[I32](fd: I32, request: ULong, ...)

struct Winsize
  var rows: U16 = 0
  var cols: U16 = 0
  var xpixel: U16 = 0
  var ypixel: U16 = 0

actor Main
  new create(env: Env) =>
    let size: Winsize = Winsize
    let get_window_size: ULong = 0x5413
    if @ioctl(0, get_window_size, size) == 0 then
      let rows = size.rows.string()
      env.out.print(rows + " rows, " + size.cols.string() + " columns")
    else
      env.err.print("Couldn't read the terminal size from standard input")
      env.exitcode(1)
    end

The first argument, 0, is the file descriptor for standard input. Passing size supplies a pointer to the struct. The terminal driver fills in its fields through that pointer. The C struct has four fields, so we provide space for all four even though we only print the rows and columns. We read them only when the call succeeds.

You can also receive a pointer to a struct from C. Suppose struct Rect *from_c(void) returns a pointer to a rectangle with two uint16_t fields. The library guarantees a non-null pointer and keeps the rectangle alive. Declare the return type as Rect and you can read its fields directly:

use @from_c[Rect]()

struct Rect
  var length: U16 = 0
  var width: U16 = 0

actor Main
  new create(env: Env) =>
    let rect = @from_c()
    env.out.print(rect.length.string() + " cm x " + rect.width.string() + " cm")

If the function can return a null pointer, use NullablePointer[Rect] as its return type so you can check before accessing the rectangle.

Returning structs by value

Now suppose our point library constructs a point and returns it by value. Put \by_value\ on the return type:

// In C: struct Point point_make(double x, double y)
use @point_make[Point \by_value\](x: F64, y: F64)

struct Point
  var x: F64 = 0
  var y: F64 = 0

actor Main
  new create(env: Env) =>
    let p = @point_make(3, 4)
    env.out.print("x: " + p.x.string() + ", y: " + p.y.string())

The generated wrapper copies the value returned by C into a Pony-allocated struct. You can then read p.x and p.y as usual. The same field restrictions apply.

A function can take a struct by value and return one by value too. Here scale_point doubles both coordinates when we pass it a factor of 2:

// In C:
// struct Point scale_point(struct Point p, double factor)
use @scale_point[Point \by_value\](p: Point \by_value\, factor: F64)

struct Point
  var x: F64 = 0
  var y: F64 = 0

actor Main
  new create(env: Env) =>
    let p: Point = Point
    p.x = 3
    p.y = 4
    let scaled = @scale_point(p, 2)
    env.out.print("x: " + scaled.x.string() + ", y: " + scaled.y.string())

Return-type Polymorphism

Suppose a C library gives you a list that stores pointers. You can put a pointer to a point in one list and a pointer to a string in another. Both lists use the same C functions because the type of an entry is void*.

struct List;

struct List* list_create(void);
void list_free(struct List* list);
void list_push(struct List* list, void* data);
void* list_pop(struct List* list);

For this example, assume list_create always returns a new list and list_push always succeeds. The list holds the pointers you give it. You still own the data they point to.

use @list_create[Pointer[_List]]()
use @list_free[None](list: Pointer[_List])
use @list_push[None](list: Pointer[_List], data: Pointer[None] tag)
use @list_pop[Pointer[None]](list: Pointer[_List])

primitive _List

struct Point
  let x: U64
  new create(x': U64) => x = x'

Let’s put a Point in one list and the characters of "Hello" in another. We keep the point in a field of Main so it stays alive while the C list holds its address. The point already exists. NullablePointer[Point](_point) gives us its address in a form we can pass to the Pointer[None] tag parameter of list_push. The characters of the string literal live for the duration of the program.

actor Main
  let _point: Point = Point(42)

  new create(env: Env) =>
    let points = @list_create()
    @list_push(points, NullablePointer[Point](_point))

    let strings = @list_create()
    @list_push(strings, "Hello".cstring())

What happens when you take the point back out? The return type in the declaration of list_pop is Pointer[None]. You can pass the pointer back to C, so this code takes the entry out and puts it straight back. If you try to read entry.x, the compiler reports that Pointer has no field named x.

let entry = @list_pop(points)
@list_push(points, entry)

C still returns the same address when you specify a return type at the call. Because we put a pointer to a Point in the first list, we can write @list_pop[Point](points) and read the x field at that address. We take the characters out as a pointer to immutable bytes and copy them into a Pony string. The program prints 42 and Hello, then frees both lists.

let first = @list_pop[Point](points)
env.out.print(first.x.string())
let text = @list_pop[Pointer[U8] val](strings)
env.out.print(recover val String.copy_cstring(text) end)

@list_free(points)
@list_free(strings)

The return type you write is a promise you make to the compiler. In this program each list has an entry when we pop it, and we know what that entry points to. If you ask for a Point from the list of strings, Pony has no way to check your promise. Complete Pony program

Variadic C functions

Some C functions take a variable number of arguments. In the signature for printf, put ... after the format string to tell Pony that the function is variadic.

use @printf[I32](fmt: Pointer[U8] tag, ...)

actor Main
  new create(env: Env) =>
    @printf("%s has %d letters\n".cstring(), "Pony".cstring(), I32(4))

The program prints Pony has 4 letters. The compiler checks the type of the format string. You’re responsible for matching the remaining arguments to the format. Here %s takes a pointer to a null-terminated string, and %d takes a C int. Keep the ... in the declaration even if you always pass the same number of arguments. On some platforms the calling convention for a variadic function differs from the one for a function with fixed parameters.

Handling C errors in Pony

A C function can report failure through its return value. To handle that failure in a Pony try block, check the return value in a partial Pony function and raise error there. For example, this C function returns zero when you pass it zero or a negative number.

#include <stdint.h>

int32_t is_positive(int32_t number)
{
  return number > 0;
}
use @is_positive[I32](number: I32)

primitive Positive
  fun apply(number: I32): I32 ? =>
    if @is_positive(number) == 0 then error end
    number

actor Main
  new create(env: Env) =>
    try
      env.out.print(Positive(1)?.string())
      env.out.print(Positive(0)?.string())
    else
      env.out.print("Expected a positive number")
    end

The first call to Positive returns 1, which Main prints. On the second call, @is_positive(0) returns zero and Positive.apply raises an error. Execution continues in the else branch, which prints Expected a positive number. The ? belongs on the partial Pony function and its calls. FFI declarations and FFI calls cannot be partial.

You can run this example by placing is_positive.c and main.pony in one directory and running ponyc there. The compiler builds the C file as a C shim. Both source files

Type signature compatibility

An FFI declaration is scoped to a Pony module. If two modules call the same C function, each module needs a declaration. The Pony types in those declarations may differ, but both must match how C receives its arguments and returns its result.

For example, memcmp compares a given number of bytes at two addresses and returns zero if the bytes match. In main.pony, the two Pointer[None] tag parameters correspond to the two const void* parameters in C. The strings "Pony" and "Pond" both start with "Pon", so comparing their first three bytes returns zero.

use cmp = "compare"
use @memcmp[I32](left: Pointer[None] tag, right: Pointer[None] tag, len: USize)

actor Main
  new create(env: Env) =>
    let left = "Pony"
    let right = "Pond"
    if @memcmp(left.cpointer(), right.cpointer(), 3) == 0 then
      env.out.print("The first three bytes match")
    end
    if not cmp.Strings.equal(left, right) then
      env.out.print("The whole strings differ")
    end

The second comparison calls Strings.equal from the compare module. The declaration of memcmp in compare/compare.pony uses Pointer[U8] tag for both addresses because this module only compares strings. The addresses are passed to C in exactly the same way. This time we compare all four bytes, so the different final letters make Strings.equal return false.

use @memcmp[I32](left: Pointer[U8] tag, right: Pointer[U8] tag, len: USize)

primitive Strings
  fun equal(left: String, right: String): Bool =>
    (left.size() == right.size()) and
      (@memcmp(left.cstring(), right.cstring(), left.size()) == 0)

Both declarations use USize for the byte count because C declares it as size_t. If you used U64, the widths would match on a 64-bit target but differ on a 32-bit target. When the two calls require incompatible parameter types, the compiler reports conflicting calls to the FFI function. To compile the example, keep main.pony in the top directory and compare.pony in its compare/ subdirectory. Run ponyc in the top directory. Complete two-module program

Calling FFI functions from Interfaces or Traits

Importing a module gives you access to its public types. Its FFI declarations stay in the module that declares them. A default method in a trait or interface can be inherited by a type in another module, so Pony rejects an FFI call in the body of the default method. The same restriction applies to default behaviours.

Try compiling this example. The compiler reports an error at the call to @printf in Foo.apply.

use @printf[I32](fmt: Pointer[U8] tag, ...)

trait Foo
  fun apply() =>
    @printf("%s\n".cstring(), "Hello from trait Foo".cstring())

actor Main is Foo
  new create(env: Env) =>
    this.apply()

You can still give every Foo the same implementation of apply. Put the FFI call in a primitive in the module that declares @printf, and call the primitive from the trait.

use @printf[I32](fmt: Pointer[U8] tag, ...)

trait Foo
  fun apply() =>
    Printf("Hello from trait Foo")

primitive Printf
  fun apply(str: String) =>
    @printf("%s\n".cstring(), str.cstring())

actor Main is Foo
  new create(env: Env) =>
    this.apply()

Now Foo.apply calls a Pony method. When Main calls this.apply(), the primitive passes the greeting to printf and the program prints Hello from trait Foo.