File: c_portdriver.html

package info (click to toggle)
erlang-doc-html 1%3A11.b.2-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 23,284 kB
  • ctags: 10,724
  • sloc: erlang: 505; ansic: 323; makefile: 62; perl: 61; sh: 45
file content (264 lines) | stat: -rw-r--r-- 8,070 bytes parent folder | download
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- This document was generated using DocBuilder 3.3.3 -->
<HTML>
<HEAD>
  <TITLE>Port drivers</TITLE>
  <SCRIPT type="text/javascript" src="../../doc/erlresolvelinks.js">
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#FF00FF"
      ALINK="#FF0000">
<CENTER>
<A HREF="http://www.erlang.se"><IMG BORDER=0 ALT="[Ericsson AB]" SRC="min_head.gif"></A>
</CENTER>
<A NAME="6"><!-- Empty --></A>
<H2>6 Port drivers</H2>

<P>This is an example of how to solve the <A HREF="example.html">example problem</A> by using a linked in port driver.
<P>
<CENTER>
<IMG ALT="port_driver" SRC="port_driver.gif"><BR>
<EM>Port Driver Communication.</EM>

</CENTER>
<A NAME="6.1"><!-- Empty --></A>
<H3>6.1 Port Drivers</H3>

<P> A port driver is a linked in driver, that is accessible as a
port from an Erlang program. It is a shared library (SO in Unix,
DLL in Windows), with special entry points. The Erlang runtime
calls these entry points, when the driver is started and when
data is sent to the port. The port driver can also send data to
Erlang.

<P> Since a port driver is dynamically linked into the emulator
process, this is the fastest way of calling C-code from Erlang.
Calling functions in the port driver requires no context
switches. But it is also the least safe, because a crash in the
port driver brings the emulator down too.
<A NAME="6.2"><!-- Empty --></A>
<H3>6.2 Erlang Program</H3>

<P> Just as with a port program, the port communicates with a Erlang
process. All communication goes through one Erlang process that
is the <STRONG>connected process</STRONG> of the port
driver. Terminating this process closes the port driver.

<P> Before the port is created, the driver must be loaded. This is
done with the function <CODE>erl_dll:load_driver/1</CODE>, with the
name of the shared library as argument.

<P> The port is then created using the BIF <CODE>open_port/2</CODE> with
the tuple <CODE>{spawn, DriverName}</CODE> as the first argument. The
string <CODE>SharedLib</CODE> is the name of the port driver. The second
argument is a list of options, none in this case.

<PRE>
-module(complex5).
-export([start/1, init/1]).

start(SharedLib) -&#62;
    case erl_ddll:load_driver(&#34;.&#34;, SharedLib) of
        ok -&#62; ok;
        {error, already_loaded} -&#62; ok;
        _ -&#62; exit({error, could_not_load_driver})
    end,
    spawn(?MODULE, init, [SharedLib]).

init(SharedLib) -&#62;
  register(complex, self()),
  Port = open_port({spawn, SharedLib}, []),
  loop(Port).
    
</PRE>

<P> Now it is possible to implement <CODE>complex5:foo/1</CODE> and
<CODE>complex5:bar/1</CODE>. They both send a message to the
<CODE>complex</CODE> process and receive the reply.

<PRE>
foo(X) -&#62;
    call_port({foo, X}).
bar(Y) -&#62;
    call_port({bar, Y}).

call_port(Msg) -&#62;
    complex ! {call, self(), Msg},
    receive
        {complex, Result} -&#62;
            Result
    end.
    
</PRE>

<P> The <CODE>complex</CODE> process encodes the message into a sequence
of bytes, sends it to the port, waits for a reply, decodes the
reply and sends it back to the caller.


<PRE>
loop(Port) -&#62;
    receive
        {call, Caller, Msg} -&#62;
            Port ! {self(), {command, encode(Msg)}},
            receive
                {Port, {data, Data}} -&#62;
                    Caller ! {complex, decode(Data)}
            end,
            loop(Port)
    end.
    
</PRE>

<P> Assumong that both the arguments and the results from the C
functions will be less than 256, a very simple encoding/decoding
scheme is employed where <CODE>foo</CODE> is represented by the byte
1, <CODE>bar</CODE> is represented by 2, and the argument/result is
represented by a single byte as well.


<PRE>
encode({foo, X}) -&#62; [1, X];
encode({bar, Y}) -&#62; [2, Y].
      
decode([Int]) -&#62; Int.
    
</PRE>

<P> The resulting Erlang program, including functionality for
stopping the port and detecting port failures, can be found in

<A TARGET="_top" HREF="complex5.erl">complex5.erl.</A>
<A NAME="6.3"><!-- Empty --></A>
<H3>6.3 C Driver</H3>

<P> The C driver is a module that is compiled and linked into a
shared library. It uses a driver structure, and includes the
header file <CODE>erl_driver.h</CODE>.

<P> The driver structure is filled with the driver name and function
pointers. It is returned from the special entry point, declared
with the macro <CODE>DRIVER_INIT(&#60;driver_name&#62;)</CODE>.

<P> The functions for receiving and sending data, are combined into
a function, pointed out by the driver structure. The data sent
into the port is given as arguments, and the data the port
sends back is sent with the C-function <CODE>driver_output</CODE>.

<P> Since the driver is a shared module, not a program, no main
function should be present. All function pointers are not used
in our example, and the corresponding fields in the
<CODE>driver_entry</CODE> structure are set to NULL.

<P> All functions in the driver, takes a handle (returned from
<CODE>start</CODE>), that is just passed along by the erlang
process. This must in some way refer to the port driver
instance.

<P> The example_drv_start, is the only function that is called with
a handle to the port instance, so we must save this. It is
customary to use a allocated driver-defined structure for this
one, and pass a pointer back as a reference.

<P> It is not a good idea to use a global variable; since the port
driver can be spawned by multiple Erlang processes, this
driver-structure should be instantiated multiple times.


<PRE>
/* port_driver.c */

#include &#60;stdio.h&#62;
#include &#34;erl_driver.h&#34;

typedef struct {
    ErlDrvPort port;
} example_data;

static ErlDrvData example_drv_start(ErlDrvPort port, char *buff)
{
    example_data* d = (example_data*)driver_alloc(sizeof(example_data));
    d-&#62;port = port;
    return (ErlDrvData)d;
}

static void example_drv_stop(ErlDrvData handle)
{
    driver_free((char*)handle);
}

static void example_drv_output(ErlDrvData handle, char *buff, int bufflen)
{
    example_data* d = (example_data*)handle;
    char fn = buff[0], arg = buff[1], res;
    if (fn == 1) {
      res = foo(arg);
    } else if (fn == 2) {
      res = bar(arg);
    }
    driver_output(d-&#62;port, &#38;res, 1);
}

ErlDrvEntry example_driver_entry = {
    NULL,                       /* F_PTR init, N/A */
    example_drv_start,          /* L_PTR start, called when port is opened */
    example_drv_stop,           /* F_PTR stop, called when port is closed */
    example_drv_output,         /* F_PTR output, called when erlang has sent */
    NULL,                       /* F_PTR ready_input, called when input descriptor ready */
    NULL,                       /* F_PTR ready_output, called when output descriptor ready */
    &#34;example_drv&#34;,              /* char *driver_name, the argument to open_port */
    NULL,                       /* F_PTR finish, called when unloaded */
    NULL,                       /* F_PTR control, port_command callback */
    NULL,                       /* F_PTR timeout, reserved */
    NULL                        /* F_PTR outputv, reserved */
};

DRIVER_INIT(example_drv) /* must match name in driver_entry */
{
    return &#38;example_driver_entry;
}


</PRE>
<A NAME="6.4"><!-- Empty --></A>
<H3>6.4 Running the Example</H3>

<P>1. Compile the C code.
<PRE>
unix&#62; gcc -o exampledrv -fpic -shared complex.c port_driver.c
windows&#62; cl -LD -MD -Fe exampledrv.dll complex.c port_driver.c
    
</PRE>

<P>2. Start Erlang and compile the Erlang code.
<PRE>
&#62; erl
Erlang (BEAM) emulator version 5.1

Eshell V5.1 (abort with ^G)
1&#62; c(complex5).
{ok,complex5}
    
</PRE>

<P>3. Run the example.
<PRE>
2&#62; complex5:start(&#34;example_drv&#34;).
&#60;0.34.0&#62;
3&#62; complex5:foo(3).
4
4&#62; complex5:bar(5).
10
5&#62; complex5:stop().
stop
    
</PRE>
<CENTER>
<HR>
<SMALL>
Copyright &copy; 1991-2006
<A HREF="http://www.erlang.se">Ericsson AB</A><BR>
</SMALL>
</CENTER>
</BODY>
</HTML>