Perl: Using Inline::C to embed C functions in your Perl scripts

Perl allows "inline" code written in other languages. This is useful because you can have native C functions interact with your Perl code. By placing your C code in the __DATA__ section of your Perl script you get clean separation between the two languages.

Note: Inline::C does not understand uint64_t in function definitions, so anything that interacts with Perl needs to use UV instead. Internally C functions can use and interact with uint64_t variables just fine.

use strict;
use warnings;
use v5.16;
use Inline 'C';

##############################################

seed_splitmix64(time());

for (1 .. 5) {
    say splitmix64();
}

##############################################

__DATA__
__C__

uint64_t x = 123456789;

void seed_splitmix64(UV seed) {
    x = seed;
}

UV splitmix64() {
    uint64_t z = (x += 0x9e3779b97f4a7c15);
    z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9;
    z = (z ^ (z >> 27)) * 0x94d049bb133111eb;

    return z ^ (z >> 31);
}

This will compile the C code into a shared object in the _Inline directory in whichever directory you instantiated your Perl script. Code is only compiled once (and where there are changes), so your script performance will be very high.



Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 216.73.217.77
To prevent spam please submit by clicking the kitten: