1. Perl
  2. XS
  3. here

How to load C library from XS file

I will explain how to read the C language library from the XS file.

Create a module with h2xs

First, create a module for XS with h2xs.

h2xs -A -n SomeModule

This will create a directory called "SomeModule". The following files and directories will be created.

Changes
lib/Makefile.PL
MANIFEST
ppport.h
README
SomeModule.xs
t/</pre>

<h3>Creating a C language library</h3>

First, let's create a C language library. Create a header file and a source file.

<b> mylib.h </b>

This is a header file. Declaring mylib_print.

<pre>
void mylib_print();

mylib.c

This is the source file. mylib_print is a function that outputs the string "mylib".

# include <stdio.h>

void mylib_print() {
  printf("mylib\n");
}

Save the header and source files and place them in the same directory where the XS files are located. Keeping it in the same directory is the point of view because there are few later settings.

XS file description

Let's write an XS file. I am calling mylib_print.

# include "EXTERN.h"
# include "perl.h"
# include "XSUB.h"

# include "ppport.h"
# include "mylib.h"

MODULE = SomeModule PACKAGE = SomeModule

void
foo (...)
  PPCODE:
{
  mylib_print();
  XSRETURN (0);
}

Modify Makefile.PL

Next, let's modify Makefile.PL a little. The bottom "OBJECT" option is commented out by default, so uncomment it. If you set "$(O_FILES)", all C language source files in the current directory will be compiled.

use ExtUtils::MakeMaker;

WriteMakefile (
    NAME =>'SomeModule',
    # VERSION_FROM =>'lib/SomeModule.pm', finds $VERSION
    # PREREQ_PM => {}, e.g., Module::Name => 1.1
    # ($] >= 5.005? # Add these new keywords supported since 5.005
      # (ABSTRACT_FROM =>'lib/SomeModule.pm', retrieve abstract from module
       AUTHOR =>'A. U. Thor <kimoto@sakura.ne.jp>') :()),
    # LIBS => [''], e.g., '-lm'
    # DEFINE =>'', e.g., '-DHAVE_SOMETHING'
    # INC =>'-I.', e.g., '-I. -I/usr/include/other'
    # OBJECT =>'$(O_FILES)', link all the C files too
);

Test script

Create a test script. This should be in the same directory where the XS files are located.

use strict;
use warnings;

use SomeModule;

SomeModule::foo ();

Compile and run

Let's compile and run it.

perl Makefile.PL
make
perl -Mblib test.pl

If the output is as follows, it is successful.

mylib

Now you can load the C library from the XS file.

Related Informatrion