Menu

Reference / Ffi

CType

finalclass
final class CType

Declares the C type of a binding's return value or parameter when PHP's own type is too coarse.

Put it on the function to describe the C return type, and on a parameter to describe that argument. The vocabulary is closed: void, bool, char, uchar, short, ushort, int, uint, long, ulong, longlong, ulonglong, size_t, ssize_t, off_t, float, double and ptr, plus multi-word C spellings such as unsigned int. Any other name, including a platform typedef like nfds_t, is a compile error. long, size_t and off_t are 64-bit.

The token decides how a narrow C result is widened to a PHP int: a callee returning int -1 must be read as -1, not 4294967295, and uint extends the other way. The token must agree with the PHP type: an integer token on a \Ffi\Ptr or string is rejected. Use 'ptr' for a handle carried as int.

#[Library('c'), Symbol('write'), CType('ssize_t')]
function write(#[CType('int')] int $fd, string $buf,
               #[CType('size_t')] int $n): int { return -1; }

Example

use Ffi\Library;
use Ffi\Symbol;
use Ffi\CType;

#[Library('c'), Symbol('atoi'), CType('int')]
function c_atoi(string $s): int { return 0; }

#[Library('c'), Symbol('strlen'), CType('size_t')]
function c_strlen(string $s): int { return 0; }

#[Library('c'), Symbol('htonl'), CType('uint')]
function c_htonl(#[CType('uint')] int $x): int { return 0; }

echo c_atoi("1234"), "\n";
echo c_atoi("-7abc"), "\n";
echo c_strlen("manticore"), "\n";
echo c_htonl(0xFFFFFFFF), "\n";

Output

1234
-7
9
4294967295

See also: Library, Symbol

Methods

__construct()Create the attribute.

__construct()#source

function __construct(public string $type)

Create the attribute.

Parameters

$type string
a C type name from the closed vocabulary, e.g. 'int', 'size_t', 'ptr'

View source