use strict;
use warnings;
use feature qw( say );
use Inline C => <<'__EOS__';
#include <stdio.h>
SV* test(SV* sv) {
float* array;
size_t num_eles;
{
STRLEN len;
char* s = SvPVbyte(sv, len);
num_eles = len/sizeof(float);
/* We can't just cast s because we could */
/* run afoul of alignment restrictions. */
array = malloc(len);
memcpy(array, s, len);
}
{
size_t i;
for (i=0; i<num_eles; ++i) {
printf("%zu %.6f\n", i, (double)(array[i]));
}
}
{
SV* return_sv = newSVpv((char*)array, num_eles*sizeof(float));
free(array);
return return_sv; /* The typemap will mortalize. */
}
}
__EOS__
my @a = (1.2, 1.3, 1.4);
say sprintf "%u %.6f", $_, $a[$_] for 0..$#a;
my $a = pack('f*', @a);
my $b = test($a);
my @b = unpack('f*', $b);
say sprintf "%u %.6f", $_, $b[$_] for 0..$#b;