[prev] [prev-tail] [tail] [up]

### 11.4 Using a pascal library from a C program

Remark:The examples in this section assume a L I N U X system; similar commands as the ones below exist for other operating systems, though. You can also call a Free Pascal generated library from a C program:

Listing: progex/ctest.pp

#include <string.h>
extern char* SubStr(const char*, int, int);
int main()
{
char *s;
int FromPos, ToPos;
s = strdup("Test");
FromPos = 2;
ToPos = 3;
printf("Result from SubStr: '%s'\n", SubStr(s, FromPos, ToPos));
return 0;
}
To compile this example, the following command can be used:

     gcc -o ctest ctest.c -lsubs

provided the code is in ctest.c.

The library can also be loaded dynamically from C, as shown in the following example:

Listing: progex/ctest2.pp

#include <dlfcn.h>
#include <string.h>
int main()
{
void *lib;
char *s;
int FromPos, ToPos;
char* (*SubStr)(const char*, int, int);
lib = dlopen("./libsubs.so", RTLD_LAZY);
SubStr = dlsym(lib, "SUBSTR");
s = strdup("Test");
FromPos = 2;
ToPos = 3;
printf("Result from SubStr: '%s'\n", (*SubStr)(s, FromPos, ToPos));
dlclose(lib);
return 0;
}
This can be compiled using the following command:

     gcc -o ctest2 ctest2.c -ldl

The -ldl tells gcc that the program needs the libdl.so library to load dynamical libraries.

[prev] [prev-tail] [front] [up]