1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2012-2013 Alexis Laferrière <alexis.laf@xymus.net>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # This module illustrates some uses of the FFI, specifically
18 # how to use extern methods. Which means to implement a Nit method in C.
22 # Returns self'th fibonnaci number
23 # implemented here in C for optimization purposes
24 fun fib
: Int import fib
`{
28 return Int_fib(self-1) + Int_fib(self-2);
31 # System call to sleep for "self" seconds
36 # Return atan2l(self, x) from libmath
37 fun atan_with
(x
: Int): Float `{
38 return atan2(self, x);
41 # This method callback to Nit methods from C code
42 # It will use from C code:
43 # * the local fib method
44 # * the + operator, a method of Int
45 # * to_s, a method of all objects
46 # * String.to_cstring, a method of String to return an equivalent char*
47 fun foo
import fib
, +, to_s
, String.to_cstring
`{
48 long self_fib = Int_fib(self);
49 long self_plus_fib = Int__plus(self, self_fib);
51 String nit_string = Int_to_s(self_plus_fib);
52 char *c_string = String_to_cstring(nit_string);
54 printf("from C: self + fib(self) = %s\n", c_string);
57 # Equivalent to foo but written in pure Nit
58 fun bar
do print
"from Nit: self + fib(self) = {self+self.fib}"
63 print
"sleeping 1 second..."
66 print
100.atan_with
(200)