Simple C-Extension example

This example shows how to create a C-Extension library on Linux® using gcc.

The command line options to compile and link shared libraries can change depending on the operating system and compiler/linker used.

The "splitext.c" C interface file

#include "f2c/fglExt.h"

int next_token(int);

UsrFunction usrFunctions[]={
  { "next_token", next_token, 1, 2 },
  { 0,0,0,0 }
};

The "split.c" file

#include <string.h>
#include "f2c/fglExt.h"

int next_token( int in_num );
int next_token( int in_num )
{
       char src[513];
       char *p;
       popvchar(src, sizeof(src));
       if (*src == '\0') {
           pushvchar("", 0);
           pushvchar("", 0);
       } else {
           p = strchr(src, ' ');
           if (p == NULL) {
               pushvchar(src, strlen(src));
               pushvchar("", 0);
           } else {
               *p = '\0';
               pushvchar(src, strlen(src));
               p++;
               pushvchar(p, strlen(p));
           }
       }
       return 2;
}

Compile the C Module and the interface file

$ gcc -c -I $FGLDIR/include -fPIC split.c
$ gcc -c -I $FGLDIR/include -fPIC splitext.c

Create the shared library

$ gcc -shared -o libsplit.so split.o splitext.o -L$FGLDIR/lib -lfgl

The program "split.4gl"

IMPORT libsplit
MAIN
    DEFINE t, r VARCHAR(100)
    LET r = "This is my first C Extension"
    WHILE TRUE
        CALL next_token(r) RETURNING t, r
        IF t IS NULL THEN
            EXIT WHILE
        END IF
        DISPLAY "token: ", t
    END WHILE
END MAIN

Compile the main module

$ fglcomp split.4gl

Run the split.42m program

$ fglrun split.42m
token: This
token: is
token: my
token: first
token: C
token: Extension