我有Perl Code和C Code,我在Perl Code中调用C函数。 我通过打包将它从Perl传递给C(就像这个http://www.perlmonks.org/?node_id=39697一样),它运行得很好!
my $p_angle = pack("f*", @angle);
但是现在我正在尝试将该数组从我的C函数返回到Perl,我希望能够用它做一些事情,例如读取值,打印......
我试图用
解压缩它my @array = unpack("f*", $entropy);
但这根本不起作用,当我打印@array时,我总是看到同样不合理的值。
所以我想我做错了,有人知道如何正确解开数组吗?
答案 0 :(得分:4)
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;