Working with Shared Libraries in PerlPresentation Transcript
Working withShared Libraries In Perl
What is a Library ?● An interface that allow you to access existed functionality without writing it over and over again● Considered non volatile tool● Usually Written by compiled languages such as C, C++ and Pascal● Not executable on its own
There are two types of libraries● Static library – Compiled* inside your code like it was written for that application● Shared Library – Compiled once, resident in memory, (usually**) providing a map table for all its shared functions* Your cpan modules considered static library.** Depends on the file format and OS
Why ? (Perl vs Shared Libraries)● Accessing user environment tools. For example: – Qt/GTK – Xlib/XCB – Libc, libstdc++ – Databases (Firebird, PostgreSQL) – etc...● Using lower level tasks with a system (inotify ...)● ...
(In Linux) There are two ways to write one● The wrong, long way that (almost) everyone use● The short, readable, easier to maintain, less buggy way, that (almost) no one use.
The wrong way ...# make it support PIC$ gcc -c -Wall -Werror -fpic ac.c# Create the shared library$ gcc -shared -o libac.so ac.c# Register the library with ld.so.conf and refresh path and cache$ sudo ldconfig# Linking$ gcc -Wall -o test main.c -lac
The right and easy waylibrary apas;function google : Byte; cdecl;begin google := 42;End;exports google;end.$ fpc apas.pas$ ls *apas*# libapas.so# Register the library with ld.so.conf and refresh path and cache$ sudo ldconfig # use the lib
How to load Shared libraries in Perl● DynaLoader – The old way● XSLoader – The new way● FFI::Raw – External way (very simplified)● Ctypes – Still in development, unstable support● Inline – Writing C/Java etc inside Perl
FFI::Raw● It is very simple● No need for .XS file (shard library for Perl ABI)● No requirement for Makefile.PL● But, lack support for few features such as struct :(