how to write a C function and be able to call it from perl -
i have been programming c while. need write c program perl can call. should have same syntax following dummy perl function: take 2 inputs, both strings (may contain binary characters, "\x00"), output new string.
of course, algorithm of function more complex, that's why need in c.
sub dummy { ($a, $b) = @_; return $a . $b; }
i have briefly looked @ swig implementation, taking input/ouput other integer not easy, hope can give concrete example.
thanks in advance.
update: got great example rob (author of inline::c module in cpan), thanks!
############################## use warnings; use strict; use devel::peek; use inline c => config => build_noisy => 1, ; use inline c => <<'eoc'; sv * foo(sv * in) { sv * ret; strlen len; char *tmp = svpv(in, len); ret = newsvpv(tmp, len); sv_catpvn(ret, tmp, len); return ret; } eoc $in = 'hello' . "\x00" . 'world'; $ret = foo($in); dump($in); print "\n"; dump ($ret); ##############################
perl has glue language called xs kind of thing. knows mappings between perl data types , c types. example, c function
char *dummy(char *a, int len_a, char *b, int len_b);
could wrapped xs code
module = foo package = foo char * dummy(char *a, int length(a), char *b, int length(b));
the foo.xs
file compiled when module installed, relevant build tool chains have support xs.
argument conversion code generated automatically, function can called in perl foo::dummy("foo", "bar")
, once xs code has been loaded perl:
package foo; use parent 'dynaloader'; foo->bootstrap;
there xs tutorial in perl documentation, , reference documentation in perlxs
.
xs choice modules, awkward one-off scripts. inline::c
module allows embed glue c code directly perl script , take care of automatic compilation whenever c code changes. however, less code can generated automatically approach.
Comments
Post a Comment