/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#ifdef WIN
#include <windows.h>
#endif
#ifdef NIX
#include <dlfcn.h>
#endif
#ifdef VMS
#include <descrip.h>
#include <lib$routines.h>
#endif

struct Data1
{
    int iv;
    char sv[50];
};

struct Data2
{
    int iv1;
    char sv1[50];
    int iv2;
    char sv2[50];
};

typedef int (*F_add)(int a, int b);
typedef int (*F_sum)(int n, int *a);
typedef char *(*F_dup)(char *s);
typedef void (*F_get_out)(int *iv, char **sv);
typedef struct Data1 *(*F_get_ret)();
typedef void (*F_chg)(struct Data2 *d);

int main()
{
#ifdef WIN
    HINSTANCE dll;
#endif
#ifdef NIX
    void *so;
#endif
    F_add add;
    F_sum sum;
    F_dup dup;
    F_get_out get_out;
    F_get_ret get_ret;
    F_chg chg;
    int a, b, c, allsix, iv;
    char *s, *s2, *sv;
    int six[] = { 1, 2, 3, 4, 5, 6 };
    struct Data1 *d1;
    struct Data2 d2;
    /* */
#ifdef WIN
    dll = LoadLibrary("stddemolib.dll");
    add = (F_add)GetProcAddress(dll, "std_add");
    sum = (F_sum)GetProcAddress(dll, "std_sum");
    dup = (F_dup)GetProcAddress(dll, "std_dup");
    get_out = (F_get_out)GetProcAddress(dll, "std_get_out");
    get_ret = (F_get_ret)GetProcAddress(dll, "std_get_ret");
    chg = (F_chg)GetProcAddress(dll, "std_chg");
#endif
#ifdef NIX
    so = dlopen("./stddemolib.so", RTLD_NOW);
    add = (F_add)dlsym(so, "std_add");
    sum = (F_sum)dlsym(so, "std_sum");
    dup = (F_dup)dlsym(so, "std_dup");
    get_out = (F_get_out)dlsym(so, "std_get_out");
    get_ret = (F_get_ret)dlsym(so, "std_get_ret");
    chg = (F_chg)dlsym(so, "std_chg");
#endif
#ifdef VMS
    $DESCRIPTOR(shrexe, "stddemolib");
    $DESCRIPTOR(S_add, "std_add");
    $DESCRIPTOR(S_sum, "std_sum");
    $DESCRIPTOR(S_dup, "std_dup");
    $DESCRIPTOR(S_get_out, "std_get_out");
    $DESCRIPTOR(S_get_ret, "std_get_ret");
    $DESCRIPTOR(S_chg, "std_chg");
    int res = lib$find_image_symbol(&shrexe, &S_add, &add);
    lib$find_image_symbol(&shrexe, &S_sum, &sum);
    lib$find_image_symbol(&shrexe, &S_dup, &dup);
    lib$find_image_symbol(&shrexe, &S_get_out, &get_out);
    lib$find_image_symbol(&shrexe, &S_get_ret, &get_ret);
    lib$find_image_symbol(&shrexe, &S_chg, &chg);
#endif
    /* */
    a = 123;
    b = 456;
    c = add(a, b);
    printf("%d\n", c);
    /* */
    allsix = sum(6, six);
    printf("%d\n", allsix);
    /* */
    s = "ABC";
    s2 = dup(s);
    printf("%s\n", s2);
    free(s2);
    /* */
    get_out(&iv, &sv);
    printf("%d %s\n", iv, sv);
    free(sv);
    /* */
    d1 = get_ret();
    printf("%d %s\n", d1->iv, d1->sv);
    /* */
    d2.iv1 = 123;
    strcpy(d2.sv1, "ABC");
    chg(&d2);
    printf("%d %s\n", d2.iv2, d2.sv2);
    /* */
    return 0;
}
