FFI (foreign function interface)

KPHP implements PHP-compatible FFI APIs.

A valid KPHP code that uses FFI will behave identically when executed with PHP interpreter.

This means that you can implement some C library wrappers in PHP via FFI and use it in both KPHP and PHP modes. These libraries can be bundled as composer packages.

If you have any questions on FFI, you should probably refer to the PHP documentation. This page contains some minimal information and KPHP-specific notes.

In case you're missing some feature that is not yet implemented in KPHP FFI system, feel free to file an issue.

What is FFI?

A foreign function interface is useful to extend KPHP with functionality that is already implemented in C.

It's particularly helpful for KPHP as you can implement unsupported PHP extensions yourself by writing a code that uses the underlying C library that is used by the PHP internal implementation.

For instance, KPHP does not come with GD module. If you look at the PHP implementation, you'll notice that it implements most functions using libgd C library. This is where FFI comes in handy: if you create a FFI class that wraps libgd, you'll have an ability yo use GD in both PHP and KPHP.

Another use case is using something completely wild and unusual, like SDL library for game development. There is an example of KPHP game that is created thanks to the FFI and SDL.

FFI is also a preferred way to extend PHP. It's less likely to break as PHP versions go up. It's also going to become faster for PHP when JIT will recognize these calls. As for KPHP, our FFI implementation is quite efficient and could become even more optimized in the future. There are a few gotchas, but you generally should not notice any performance problems with it.

KPHP-specific features, extensions

Type hints

As with anything else, KPHP wants to have more types information to build your code.

All FFI-related types should be annotated with special annotations:

  • ffi_cdata<scope_name, type_expr> for \FFI\CData
  • ffi_scope<scope_name> for \FFI class instances

For ffi_cdata<>, you can use a pointer-type expression, builtin type name, struct name and any other supported C type expression. For instance, ffi_cdata<foo, union Event**> is a valid ffi_cdata declaration.

This example should make it obvious when you need to use either of them:

<?php

/** @param ffi_scope<example> */
function f($lib) {
  $foo = $lib->new('struct Foo');
  $foo->value = 1204;
  g($foo);
  g_ptr(\FFI::addr($foo));
}

/** @param ffi_cdata<example, struct Foo> */
function g($foo) { var_dump($foo->value); }

/** @param ffi_cdata<example, struct Foo*> */
function g_ptr($foo) { var_dump($foo->value); }

$cdef = FFI::cdef('
  #define FFI_SCOPE "example"
  struct Foo { int value; };
');

f($cdef);

If you need to describe a builtin C type that is not bound to any particular FFI scope, use default FFI scope name “C”:

/**
 * Since void* is a global type, we can use "C" scope name to avoid any dependency
 * on a custom FFI scope.
 *
 * @param ffi_cdata<C, void*> $ptr
 */
function as_uint8_ptr($ptr) {
  FFI::cast('uint8_t*', $ptr);
}

KPHP will give compile-time error if types are not compatible or some requested type or function are not declared as a part of the FFI cdef source.

Unlike in PHP, it's possible to use FFI::scope without opcache preloading. In order to be compatible with PHP, you need to provide a separate preloading script and run it appropriately.

When \FFI::cdef or \FFI::load C sources don't contain a FFI_SCOPE directive, the scope name will be automatically generated, so it will be almost impossible to spell that ffi_scope type properly. For both PHP and KPHP it's preferable to use named scopes.

Array types

It is possible to allocate both fixed size and dynamic sized arrays in FFI:

$fixed_arr = \FFI::new('int32_t[8]');

$size = 15;
$dynamic_arr = \FFI::new("int32_t[$size]");
$dynamic_arr2 = \FFI::new('int32_t[' . $size . ']');

To specify that type in a type hint, use this notation:

class Example {
  /** @var ffi_cdata<C, int32_t[]> */
  public $ffi_arr;

  /**
   * A PHP array of FFI arrays
   * @var ffi_cdata<C, int32_t[]>[]
   */
  public $array_of_ffi_arrays;
}

Note that you can pass fixed size arrays as dynamic size array types.

It is possible to cast a T[] array to a T* pointer. Unlike the pointers acquired from FFI::cast(), arrays retain data ownership. So while it is usually safe to pass T[] as T* as a function argument, it is better to return these values as T[] to avoid dangling pointers.

Some operations require kphp polyfills due to the different syntax.

// get element of an array (or dereference a pointer at given offset)
// identical to $arr[$index];
$result = ffi_array_get($arr, $index);

// set element of an array (or write at the pointer at given offset)
// identical to $arr[$index] = $value;
ffi_array_set($arr, $index, $value);

// like FFI::memcpy, but the source argument is a string, not FFI\CData
// identical to FFI::memcpy($cdata, $php_string, $size);
ffi_memcpy_string($cdata, $php_string, $size);

// like FFI::cast, but the source argument is int, not FFI\CData
// identical to FFI::cast('void*', $addr);
// $addr should be a value obtained by ffi_cast_ptr2addr
ffi_cast_addr2ptr($addr)

// like FFI::cast, but the destination type is uintptr_t-like scalar
// identical to FFI::cast('uintptr_t', $ptr)
// $ptr should be a CData holding void* pointer
ffi_cast_ptr2addr($ptr)

Auto conversions

If PHP applies an auto conversion, KPHP would do it too.

There are 2 kinds of auto conversions:

  • php2c – when a PHP value is being passed or assigned to a C value
  • c2php – when a C value is being read (so it becomes a PHP value)

Many php2c and c2php conversions are symmetrical, but there are a few special rules we should keep in mind.

When a php2c can happen:

  • Passing C function argument
  • Assigning to a C struct/union field
  • Assigning to a pseudo cdata property of C scalar types (like int8_t)
PHP type C type Note
int int8_t-int64_t, int, uint, etc. A trivial cast (may truncate).
float float, double A trivial cast.
bool bool No-op.
string(1) char Run time error if string length is not 1.
string (*) const char* Doesn't make a copy.
ffi_cdata<$scope, T> T Alloc-free.
ffi_cdata<$scope, T*> T* Alloc-free.