Something cool about Perl 6 every day

Primary Menu

Day 15 – Calling native libraries from Perl 6

If you’ve used Perl 5 for any length of time, you’ve probably encountered a package with “::XS” in the name. Maybe you’ve even written one, in which case you can skip this paragraph. XS is Perl 5’s way of calling into native code (C libraries), and it works great for what it does. Writing such modules takes effort though; there’s C code and compilers involved, and it’s not much fun if you just want to get something working with a minimum of effort.

Perl 6 puts a lot of effort into letting you be lazy. That goes for using foreign code too. Let’s tell it we’re going to do that:

#!/usr/bin/env perl6
use v6;
use NativeCall;

That’s it. NativeCall does the hard work of talking to C libraries; you don’t need to manually compile anything. For Rakudo, you just need to install zavolaj.

First off, NativeCall needs to know how to talk to the C library. At present it knows how to translate to/from strings, numbers, and a thing called OpaquePointer. That last one is for things like database connection handles that you should only poke with a 10-foot pole.

We’re dealing with weird structs and a socket connection in this code, so let’s pretend those are subclasses of OpaquePointer. These don’t have any effect on the code, but it’ll be easier to follow:

Now the C functions we’re using, in alphabetical order. One of these is slightly different from the rest – the original C code expects a **char to be passed in, or in other words a place in memory to write a string. We give it a Str is rw, and it just works.