1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
|
package FFI::C;
use strict;
use warnings;
use 5.008001;
use Carp ();
use Ref::Util qw( is_ref is_plain_arrayref is_plain_hashref );
# ABSTRACT: C data types for FFI
our $VERSION = '0.15'; # VERSION
our %ffi;
sub _ffi_get
{
my($filename) = @_;
$ffi{$filename} ||= do {
require FFI::Platypus;
FFI::Platypus->new( api => 1 );
};
}
sub ffi
{
my($class, $new) = @_;
my(undef, $filename) = caller;
if($new)
{
Carp::croak("Already have an FFI::Platypus instance for $filename")
if defined $ffi{$filename};
return $ffi{$filename} = $new;
}
_ffi_get($filename);
}
our $def_class;
sub _gen
{
shift;
my($class, $filename) = caller;
my($name, $members);
my %extra = is_plain_hashref $_[-1] ? %{ pop() } : ();
if(@_ == 2 && !is_ref $_[0] && is_plain_arrayref $_[1])
{
($name, $members) = @_;
}
elsif(@_ == 1 && is_plain_arrayref $_[0])
{
$name = lcfirst [split /::/, $class]->[-1];
$name =~ s/([A-Z]+)/'_' . lc($1)/ge;
$name .= "_t";
($members) = @_;
}
else
{
my($method) = map { lc $_ } $def_class =~ /::([A-Za-z]+)Def$/;
Carp::croak("usage: FFI::C->$method([\$name], \\\@members)");
}
$def_class->new(
_ffi_get($filename),
%extra,
name => $name,
class => $class,
members => $members,
);
}
sub struct
{
require FFI::C::StructDef;
$def_class = 'FFI::C::StructDef';
goto &_gen;
}
sub union
{
require FFI::C::UnionDef;
$def_class = 'FFI::C::UnionDef';
goto &_gen;
}
sub array
{
require FFI::C::ArrayDef;
$def_class = 'FFI::C::ArrayDef';
goto &_gen;
}
sub enum
{
(undef) = shift;
my $name = defined $_[0] && !is_ref $_[0] ? shift : undef;
my @values = defined $_[0] && is_plain_arrayref $_[0] ? @{shift()} : ();
my %config = defined $_[0] && is_plain_hashref $_[0] ? %{shift()} : ();
my($class, $filename) = caller;
unless(defined $name)
{
$name = lcfirst [split /::/, $class]->[-1];
$name =~ s/([A-Z]+)/'_' . lc($1)/ge;
$name .= "_t";
}
my $ffi = _ffi_get($filename),
$config{package} ||= $class;
my @maps;
$config{maps} = \@maps;
my $rev = $config{rev} ||= 'str';
$ffi->load_custom_type('::Enum', $name, \%config, @values);
my($str_lookup, $int_lookup, $type) = @maps;
require FFI::C::Def;
$ffi->def('FFI::C::EnumDef', $name,
FFI::C::EnumDef->new(
str_lookup => $str_lookup,
int_lookup => $int_lookup,
type => $type,
rev => $rev,
)
);
}
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
FFI::C - C data types for FFI
=head1 VERSION
version 0.15
=head1 SYNOPSIS
In C:
#include <stdint.h>
typedef struct {
uint8_t red;
uint8_t green;
uint8_t blue;
} color_value_t;
typedef struct {
char name[22];
color_value_t value;
} named_color_t;
typedef named_color_t array_named_color_t[4];
typedef union {
uint8_t u8;
uint16_t u16;
uint32_t u32;
uint64_t u64;
} anyint_t;
In Perl:
use FFI::C;
package ColorValue {
FFI::C->struct([
red => 'uint8',
green => 'uint8',
blue => 'uint8',
]);
}
package NamedColor {
FFI::C->struct([
name => 'string(22)',
value => 'color_value_t',
]);
}
package ArrayNamedColor {
FFI::C->array(['named_color_t' => 4]);
};
my $array = ArrayNamedColor->new([
{ name => "red", value => { red => 255 } },
{ name => "green", value => { green => 255 } },
{ name => "blue", value => { blue => 255 } },
{ name => "purple", value => { red => 255,
blue => 255 } },
]);
# dim each color by 1/2
foreach my $color (@$array)
{
$color->value->red ( $color->value->red / 2 );
$color->value->green( $color->value->green / 2 );
$color->value->blue ( $color->value->blue / 2 );
}
# print out the colors
foreach my $color (@$array)
{
printf "%s [%02x %02x %02x]\n",
$color->name,
$color->value->red,
$color->value->green,
$color->value->blue;
}
package AnyInt {
FFI::C->union([
u8 => 'uint8',
u16 => 'uint16',
u32 => 'uint32',
u64 => 'uint64',
]);
}
my $int = AnyInt->new({ u8 => 42 });
print $int->u32;
=head1 DESCRIPTION
This distribution provides tools for building classes to interface for common C
data types. Arrays, C<struct>, C<union> and nested types based on those are
supported.
Core L<FFI::Platypus> also provides L<FFI::Platypus::Record> for manipulating and
passing structured data. Typically you want to use L<FFI::C> instead, the main
exception is when you need to pass structured data by value instead of by
reference.
To work with C APIs that work with C file pointers you can use
L<FFI::C::File> and L<FFI::C::PosixFile>. For C APIs that expose the POSIX
C<stat> structure use L<FFI::C::Stat>.
=head1 METHODS
=head2 ffi
FFI::C->ffi($ffi);
my $ffi = FFI::C->ffi;
Get or set the L<FFI::Platypus> instance used for the current Perl file
(C<.pl> or C<.pm>).
By default a new Platypus instance is created the on the first call to
C<ffi>, or when a new type is created with C<struct>, C<union> or C<array>
below, so if you want to use your own Platypus instance make sure that
you set it as soon as possible.
The Platypus instance is file scoped because scoping on just one package
doesn't make sense if you are defining multiple types in one file since
each type must be in its own package. It also doesn't make sense to make
the Platypus instance global, because different distributions would
conflict.
=head2 struct
FFI::C->struct($name, \@members);
FFI::C->struct(\@members);
Generate a new L<FFI::C::Struct> class with the given C<@members> into
the calling package. (C<@members> should be a list of name/type pairs).
You may optionally give a C<$name> which will be used for the
L<FFI::Platypus> type name for the generated class. If you do not
specify a C<$name>, a C style name will be generated from the last segment
in the calling package name by converting to snake case and appending a
C<_t> to the end.
As an example, given:
package MyLibrary::FooBar {
FFI::C->struct([
a => 'uint8',
b => 'float',
]);
};
You can use C<MyLibrary::FooBar> via the file scoped L<FFI::Platypus> instance
using the type C<foo_bar_t>.
my $foobar = MyLibrary::FooBar->new({ a => 1, b => 3.14 });
$ffi->function( my_library_func => [ 'foo_bar_t' ] => 'void' )->call($foobar);
=head2 union
FFI::C->union($name, \@members);
FFI::C->union(\@members);
This works exactly like the C<struct> method above, except a
L<FFI::C::Union> class is generated instead.
=head2 array
FFI::C->array($name, [$type, $count]);
FFI::C->array($name, [$type]);
FFI::C->array([$type, $count]);
FFI::C->array([$type]);
This is similar to C<struct> and C<union> above, except L<FFI::C::Array> is
generated. For an array you give it the member type and the element count.
The element count is optional for variable length arrays, but keep in mind
that when you create such an array you do need to provide a size.
=head2 enum
FFI::C->enum($name, \@values, \%config);
FFI::C->enum(\@values, \%config);
FFI::C->enum(\@values, \%config);
FFI::C->enum(\@values);
Defines an enum. The C<@values> and C<%config> are passed to
L<FFI::Platypus::Type::Enum>, except the constants are exported
to the calling package by default.
=head1 EXAMPLES
=head2 unix time struct
use FFI::Platypus 1.00;
use FFI::C;
my $ffi = FFI::Platypus->new(
api => 1,
lib => [undef],
);
FFI::C->ffi($ffi);
package Unix::TimeStruct {
FFI::C->struct(tm => [
tm_sec => 'int',
tm_min => 'int',
tm_hour => 'int',
tm_mday => 'int',
tm_mon => 'int',
tm_year => 'int',
tm_wday => 'int',
tm_yday => 'int',
tm_isdst => 'int',
tm_gmtoff => 'long',
_tm_zone => 'opaque',
]);
# For now 'string' is unsupported by FFI::C, but we
# can cast the time zone from an opaque pointer to
# string.
sub tm_zone {
my $self = shift;
$ffi->cast('opaque', 'string', $self->_tm_zone);
}
# attach the C localtime function
$ffi->attach( localtime => ['time_t*'] => 'tm', sub {
my($inner, $class, $time) = @_;
$time = time unless defined $time;
$inner->(\$time);
});
}
# now we can actually use our My::UnixTime class
my $time = Unix::TimeStruct->localtime;
printf "time is %d:%d:%d %s\n",
$time->tm_hour,
$time->tm_min,
$time->tm_sec,
$time->tm_zone;
=head1 CAVEATS
L<FFI::C> objects must be passed into C via L<FFI::Platypus> by pointers.
So-called "pass-by-value" is not and will not be supported. For
"pass-by-value" record types, you should instead use L<FFI::Platypus::Record>.
=head1 SEE ALSO
=over 4
=item L<FFI::C>
=item L<FFI::C::Array>
=item L<FFI::C::ArrayDef>
=item L<FFI::C::Def>
=item L<FFI::C::File>
=item L<FFI::C::PosixFile>
=item L<FFI::C::Struct>
=item L<FFI::C::StructDef>
=item L<FFI::C::Union>
=item L<FFI::C::UnionDef>
=item L<FFI::C::Util>
=item L<FFI::Platypus::Record>
=back
=head1 AUTHOR
Graham Ollis <plicease@cpan.org>
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2020-2022 by Graham Ollis.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
|