how to write a C function and be able to call it from perl
10:07 06 Apr 2014

I have been programming C for a while. Now I need to write a C program that perl can call. It should have the same syntax as the following dummy perl function: Take two inputs, both are strings (may contain binary characters, even "\x00"), output a new string.

Of course, algorithm of the function will be more complex, that's why I need to do it in C.

sub dummy {
    my ($a, $b) = @_;
    return $a . $b;
}

I have briefly looked at SWIG for the implementation, but taking input/ouput other than an integer is not easy, hope someone can give a concrete example.

Thanks in advance.

UPDATE: Got a great example from Rob (author of the 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

my $in = 'hello' . "\x00" . 'world';
my $ret = foo($in);


Dump($in);
print "\n";
Dump ($ret);

##############################
perl