Created
November 5, 2013 20:26
-
-
Save ivan-krukov/7325637 to your computer and use it in GitHub Desktop.
Using Perl Inline::CPP and perlapi to pass around array data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the gist.
Regarding comment on the line #3: just wrap the word 'CPP' with quotes or put it into a list.