Skip to content

Instantly share code, notes, and snippets.

@ivan-krukov
Created November 5, 2013 20:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivan-krukov/7325637 to your computer and use it in GitHub Desktop.
Save ivan-krukov/7325637 to your computer and use it in GitHub Desktop.
Using Perl Inline::CPP and perlapi to pass around array data
#!/usr/bin/perl
use warnings;
#not sure how to use strict here - does not allow bareword in "Inline CPP"
use Inline CPP;
my @data = (0..10);
my $result_ref = do_stuff(\@data);
my @result = @$result_ref;
print "@result\n";
__END__
__CPP__
#include <iostream>
using namespace std;
float * av_to_float_array (AV * perl_array) {
int size = av_len(perl_array);
float * array = new float [size];
for (int i = 0; i < size; i ++ ) {
SV ** scalar_ptr = av_fetch(perl_array,i,0);
float number = SvNV(*scalar_ptr);
array[i]=number;
}
return array;
}
AV * float_array_to_av (float * array, int size) {
AV * perl_array = newAV();
for (int i = 0; i < size; i++) {
SV * scalar = newSVnv(array[i]);
av_push(perl_array,scalar);
}
return perl_array;
}
float * mul (float * a, float * b, int size) {
float * c = new float [size];
for (int i = 0; i < size; i++) {
c[i]=a[i]*b[i];
}
return c;
}
AV * do_stuff(AV * perl_array) {
float * data = av_to_float_array(perl_array);
int size = av_len(perl_array);
float * result = mul(data,data,size);
return float_array_to_av(result,size);
}
@haodemon
Copy link

Thanks for the gist.

Regarding comment on the line #3: just wrap the word 'CPP' with quotes or put it into a list.

use Inline 'CPP';
use Inline qw/CPP/;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment