C Perl XS

If you program in Perl and learn XS is like you have super powers.

Perl has a big amount of modules available, but sometimes you need a library from C, in my case that library was Duktape to embed a JS interpreter in my application to be able to use a scrapped function from the Youtube video player to implement download videos with obfuscated signatures in Peertube-dl.

XS allows you to embed C libraries in Perl, this opens the door to many applications from writting programs using GTK to fast a critical in performance subroutine, tons of CPAN modules use it to extend the Perl’s capabilities.

The main resources to learn XS are: and

This is how a very basic XS Perl module look:

#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#include "duktape.h"
#include "duk_config.h"
#include "javascript_builtins.h"

MODULE = Peertube::DL::Javascript  PACKAGE = Peertube::DL::Javascript

SV *
        duk_context *context = duk_create_heap_default();
        if (context) {
            duk_push_c_function(context, js_builtin_print, 1);
            duk_put_global_string(context, "print");
            RETVAL = newSVuv((size_t)context);
        } else {
            RETVAL = &PL_sv_undef;

This is how the loader Perl module would look:

package Peertube::DL::Javascript;

use strict;
use warnings;

use feature 'say';

use XSLoader;
use Data::Dumper;


sub new {
    my $class = shift;
    my $self  = bless {}, $class;
    $self->{___ContextPrivateDONOTTOUCH} =
    return $self;

You can check for a complete example on the source of Peertube-dl:

By sergiotarxz

I am a software developer with high interest on free software.

Leave a Reply

Your email address will not be published. Required fields are marked *