Here is the C code used for the above example, including build steps.

The header file (xswrap.h)

int mult (int x, int y); void speak (const char* str); unsigned char* arr ();

The .c file (xswrap.c)

#include <stdio.h> #include <stdlib.h> int mult (int x, int y){ return x * y; } void speak (const char* str){ printf("%s\n", str); } unsigned char* arr (){ unsigned char* list = malloc(sizeof(unsigned char) * 3); int i; for (i=0; i<3; i++){ list[i] = i; } return list; }

The entry point file (main.c) for testing the lib

#include <stdio.h> #include "xswrap.h" int main (){ int ret = mult(5, 5); printf("%d\n", ret); speak("hello, world!"); unsigned char* list = arr(); int i; for (i=0; i<3; i++){ printf("%d\n", list[i]); } return 0; }

The build/install script (build.sh)

#!/bin/sh gcc -c -fPIC xswrap.c gcc -shared -fPIC -Wl,-soname,libxswrap.so -o libxswrap.so xswrap.o -l +c sudo cp libxswrap.so /usr/lib sudo cp xswrap.h /usr/local/include

Done!

The library and its header file are both now put into directories in your PATH.

To compile the test program:

gcc -o test main.c -lxswrap

...run it:

./test

You're now ready to wrap the library using Perl and XS per the OP.


In reply to Re: Wrapping a C shared library with Perl and XS by stevieb
in thread Wrapping a C shared library with Perl and XS by stevieb

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.