/* c16test2.c (emx+gcc) */

/* Call 16-bit function linked at run time. */

#include <stdio.h>
#include <stdlib.h>
#define INCL_DOSMODULEMGR
#include <os2.h>

static _far16ptr add_addr = 0;

short add (int x, int y)
{
  return ((short)(_THUNK_C_PROLOG (2+2);
                  _THUNK_C_SHORT (x);
                  _THUNK_C_SHORT (y);
                  _THUNK_C_CALLI (add_addr)));
}


/* Load c16.dll and get the address of add(). */

static void link_add (void)
{
  CHAR buf[32];
  PFN pfn;
  ULONG rc;
  HMODULE hmod;

  rc = DosLoadModule (buf, sizeof (buf), "c16", &hmod);
  if (rc != 0)
    {
      fprintf (stderr, "DosLoadModule failed, rc=%lu\n", rc);
      exit (2);
    }
  rc = DosQueryProcAddr (hmod, 0, "_ADD", &pfn);
  if (rc != 0)
    {
      fprintf (stderr, "DosQueryProcAddr failed, rc=%lu\n", rc);
      exit (2);
    }
  add_addr = _emx_32to16 (pfn);
}


int main (void)
{
  link_add ();
  printf ("2+3=%d\n", add (2, 3));
  return 0;
}
