File: pl-dll.c

package info (click to toggle)
swi-prolog 3.1.0-2
  • links: PTS
  • area: main
  • in suites: slink
  • size: 8,772 kB
  • ctags: 12,869
  • sloc: ansic: 43,657; perl: 12,577; lisp: 4,359; sh: 1,534; makefile: 798; awk: 14
file content (112 lines) | stat: -rw-r--r-- 1,861 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*  $Id: pl-dll.c,v 1.5 1998/02/18 13:56:46 jan Exp $

    Part of SWI-Prolog.

    Purpose: Windows DDL interface
*/

#if defined(__WINDOWS__) || defined(__WIN32__)

#include "windows.h"
#include "pl-incl.h"
#include <stdio.h>

#ifdef O_DLL

extern char *WinError(void);

#define MAX_DLL_INSTANCES	32	/* handle allocation */

static HINSTANCE dll[MAX_DLL_INSTANCES];

static int
allocDllHandle(HINSTANCE handle)
{ int i;

  for(i=0; i<MAX_DLL_INSTANCES; i++)
  { if ( !dll[i] )
    { dll[i] = handle;
      return i;
    }
  }

  warning("DLL manager: out of handles");
  return -1;
}


static int
get_dll_handle(term_t handle, int *hdl)
{ int i;

  if ( PL_get_integer(handle, &i) &&
       i >= 0 && i < MAX_DLL_INSTANCES && dll[i] )
  { *hdl = i;

    succeed;
  }

  fail;
}


static word
dll_warning(char *fmt)
{ return warning("%s failed: %s", fmt, WinError());
}



word
pl_open_dll(term_t name, term_t handle)
{ HINSTANCE h;
  char *s;

  if ( !PL_get_chars(name, &s, CVT_ALL) )
    return warning("open_dll/2: illegal name");

  if ( (h = LoadLibrary(s)) )
  { int plhandle = allocDllHandle(h);

    return PL_unify_integer(handle, plhandle);
  }

  return dll_warning("open_dll/2");
}


word
pl_close_dll(term_t handle)
{ int i;

  if ( !get_dll_handle(handle, &i) )
    return warning("close_dll/1: illegal handle");
  
  FreeLibrary(dll[i]);
  dll[i] = NULL;

  succeed;
}


word
pl_call_dll_function(term_t handle, term_t funcname)
{ int i;
  FARPROC proc;
  char *fname;

  if ( !get_dll_handle(handle, &i) )
    return warning("call_dll_function/2: illegal handle");
  if ( !PL_get_chars(funcname, &fname, CVT_ALL) )
    return warning("call_dll_function/2: illegal function name");
  
  if ( !(proc = GetProcAddress(dll[i], fname)) )
    fail;

  (*proc)();

  succeed;
}

#endif /*O_DLL*/
#endif /*defined(__WINDOWS__) || defined(__WIN32__)*/