Using extern C code from Lustre programs with lv6
Suppose for example that you want to define a random
node from a lustre file named
use_random.lus
. One can do it like that:
unsafe extern function c_rand(x:int) returns (res:int);
We declare it as
- a
function
since it needs no memory unsafe
as it performs side-effects (for the PRNG, a.k.a., the Pseudo Random Numbers Generator)
Then we can use this node in our lustre code as regular nodes.
unsafe function random(x:int) returns (res:int);
let
res = c_rand(x);
tel
Let’s compile it with the -2c option the random.lus
program that contains the code above:
lv6 random.lus -n random -dir random
This will create in the random
directory (because of the -dir
parameter) a bunch of C files.
One of them is named random_random_ext.c
and contains something like:
#include "random_random.h"
void random_random_step(_integer x,_integer *res){
// finish me
}
As you are hinted to, you can finish it, for example like that:
#include "random_random.h"
#include <stdlib.h>
#include <assert.h>
void random_random_step(_integer x,_integer *res){
assert (0 < x );
*res = (rand() % x);
}
and then compile everything, for example using the random/random.sh
script that was generated
by lv6
.
sh random/random.sh
that ougth to generated the random.exec
executable:
./random.exec