Calling C functions from programs

C-Extensions functions can be called from the program in the same way that you call a BDL function.

The C functions that can be called from programs must use the following signature:
int function-name( int )

Here function-name must be written in lowercase letters. The fglcomp compiler converts all BDL function names (following a CALL keyword) to lowercase.

The C function must be declared in the usrFunctions array in the C interface file.

Important: Parameters and return values must be pushed/popped on the runtime stack, by using the stack functions. Parameters passed to the C function must be popped in the reverse order of the BDL call list: CALL c_fct( A, B, C ) => pop C, B, A. However, values returned from the C function must be pushed in the same order as in the BDL returning clause: push A, B, C => CALL c_fct() RETURNING A, B, C.

In this code example, the C-Extension module mycext.c defines the c_fct() function:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "f2c/fglExt.h"

int c_fct( int n );

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

int c_fct( int n )
{
   int rc;
   float price;
   char name[31];
   if (n != 2) exit(1);
   popflo(&price);
   popvchar(name, sizeof(name));
   printf(">> [%s] price:%f\n", name, price);
   pushint( strlen(name) );
   price = price * 2;
   pushflo( &price );
   return 0;
}

The C-Extension library is imported by the BDL module with IMPORT:

IMPORT mycext

MAIN
    DEFINE len INT, price2 FLOAT
    CALL c_fct("Hand gloves", 120.50)
         RETURNING len, price2
    DISPLAY "len = ", len
    DISPLAY "price2 = ", price2
END MAIN
Compilation and execution example on a Linux® system:
$ gcc -I $FGLDIR/include -shared -fPIC -o mycext.so mycext.c

$ fglcomp myprog.4gl

$ fglrun myprog.42m
>> [Hand gloves] price:120.500000
len =          11
price2 =                   241.0