call#
Invoke a C function from an opened library and return its result.
Synopsis#
my $n = Peta::FFI::call($lib, "strlen", "(p)L", "hello"); # 5
my $r = Peta::FFI::call($lib, "sqrt", "(d)d", 2.0); # 1.4142...
my $s = Peta::FFI::call($lib, "getenv", "(p)p", "PATH"); # /usr/bin:...
Peta::FFI::call($lib, "srand", "(i)v", 42); # void return
Arguments#
$lib- handle returned bydlopen.$func- symbol name to look up in the library, or the address of a function: a pointer C handed out, such as an entry of a table of callbacks, which has no name to look up.$sig- signature string(args)ret; see the module-level type-code table.the remaining arguments - one value per type code in
args, coerced to the matching C type before the call.
What you get back#
A single scalar whose shape depends on the return type:
the integer types,
b- an integer; perl’s true or false.d/f/D- a float (a long double rounded to one).cf/cd-[re, im].p- the returnedconst char *copied into a Perl string;undefif the C function returnedNULL.o- the address;0forNULL.v-1, so the call chains naturally in boolean contexts.P- pointer returned as a string (same rules asp).*T- a reference to the value it points to;T[N]- a reference to an array of the N values;undefforNULL.{Class}- a new record object;*{Class}- a copy of the record it points to,undefforNULL.
Output buffers (P)#
A P argument that is a reference to a scalar passes that scalar’s own bytes, and after the call the scalar holds what the callee wrote there - as many bytes as it had: my $buf = "\0" x 64; call(..., \$buf). Any other P argument is a zeroed buffer the callee may write and nobody reads, as long as the string passed (minimum 16 bytes) or as many bytes as the number says.
Pointers and arrays#
A *T argument is a reference to a scalar, which the callee reads and writes - an out-parameter, \my $n - or undef for NULL; a reference to an array passes its elements. A T[N] argument is a reference to an array of N values, and T[] one of any length; after the call the array holds what the callee left there.
Edge cases#
Wrong argument count - croaks with
Peta::FFI::call FNAME: expected N args, got M.Bad signature string - croaks with
FFI signature error: ...describing the offending character or missing).Symbol not found - croaks with
Peta::FFI::call: symbol not found: FNAMEor the message reported bydlerror.Incorrect type codes - calling a function with a signature that does not match its real prototype is undefined behaviour. Check the C header before writing the signature.
String argument contains a null byte - croaks with
Peta::FFI::call FNAME: CString error: ....A handle of the wrong class, or a released one - croaks before the call.
call parses the signature, looks the symbol up and prepares the call interface every time; a function called more than a few times is better prepared once with function or attach.