How to write a C function and be able to call it from perl

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 lines (can contain binary characters, even "\ x00"), output a new line.

Of course, the function algorithm will be more complex, so I need to do this in C.

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

I briefly reviewed SWIG for implementation, but making input / output different from the whole is not easy, I 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); ############################## 
+7
perl
source share
1 answer

Perl has a glue language called XS for this kind of thing. He knows about the mappings between Perl data types and C types. For example, the C function

 char *dummy(char *a, int len_a, char *b, int len_b); 

can be wrapped with XS code

 MODULE = Foo PACKAGE = Foo char * dummy(char *a, int length(a), char *b, int length(b)); 

The Foo.xs file will be compiled when the module is installed, all the corresponding assembly tool chains support XS.

The argument conversion code will be generated automatically, so the function can be called in Perl as Foo::dummy("foo", "bar") as soon as the XS code has been loaded with Perl:

 package Foo; use parent 'DynaLoader'; Foo->bootstrap; 

The perl documentation has an XS tutorial and reference documentation in perlxs .

XS is a good choice for modules, but inconvenient for one-time scripts. The Inline::C module allows you to embed C glue code directly into your Perl script and will take care of automatic compilation whenever C code changes. However, with this approach, less code is automatically generated.

+11
source share

All Articles