1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2012 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 native interface, specifically
18 # how to use extern methods. Which means to implement a Nit method in C.
20 # Steps to use extern methods:
21 # 1. Write the Nit module (like this file), define extern methods
22 # with "is extern" and identify possible callbacks with "import".
23 # 2. Run ithe "nits" program on the Nit module, it will generate
24 # two files, extern_methods.stub.[ch] files.
25 # 3. Modify those files to implement Nit methods in C.
26 # 4. Rename the stub files to extern_methods.nit.c and extern_methods.nit.h.
30 # Returns self'th fibonnaci number
31 # implemented here in C for optimization purposes
32 fun fib
: Int is extern
34 # System call to sleep for "self" seconds
37 # Return atan2l( self, x ) from libmath
38 fun atan_with
( x
: Int ) : Float is extern
40 # This method callback to Nit methods from C code
41 # It will use from C code:
42 # * the local fib method
43 # * the + operator, a method of Int
44 # * to_s, a method of all objects
45 # * String::to_cstring, a method of String to return an equivalent char*
46 fun foo
is extern import fib
, +, to_s
, String::to_cstring
48 # Equivalent to foo but written in pure Nit
49 fun bar
do print
"from Nit: self + fib(self) = {self+self.fib}"
54 print
"sleeping 1 second..."
57 print
100.atan_with
( 200 )