Interfacing an External C Program with a Port

We’ll start with some simple C code. example1.c contains two functions. The first function computes the sum of two integers, and the second computes twice its argument.

ports/example1.c
 
int​ sum(​int​ x, ​int​ y){
 
return​ x+y;
 
}
 
 
int​ twice(​int​ x){
 
return​ 2*x;
 
}

Our final goal is to call these routines from Erlang. We’d like to be able to call them as follows:

 
X1 = example1:sum(12,23),
 
Y1 = example1:twice(10),

As far as the user is concerned, example1 is an Erlang module, and therefore all details of the interface to the C program should be hidden inside the module example1.

To implement this, we need to turn function calls such as sum(12,23) and twice(10) into sequences of bytes ...

Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.