1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2013 Matthieu Lucas <lucasmatthieu@gmail.com>
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 sample has been implemented to show you how simple is it to play
18 # with native callbacks (C) through an high level with NIT program.
20 module callback_monkey
32 MonkeyActionCallable toCall;
38 // Method which reproduce a callback answer
39 // Please note that a function pointer is only used to reproduce the callback
40 void cbMonkey(CMonkey *mkey, void callbackFunc(CMonkey*, MonkeyAction*), MonkeyAction *data)
43 callbackFunc( mkey, data );
46 // Back of background treatment, will be redirected to callback function
47 void nit_monkey_callback_func( CMonkey *mkey, MonkeyAction *data )
49 // To call a your method, the signature must be written like this :
50 // <Interface Name>_<Method>...
51 MonkeyActionCallable_wokeUp( data->toCall, mkey, data->message );
55 # Implementable interface to get callback in defined methods
56 interface MonkeyActionCallable
57 fun wokeUp
( sender
:Monkey, message
: Object) is abstract
60 # Defining my object type Monkey, which is, in a low level, a pointer to a C struct (CMonkey)
61 extern Monkey `{ CMonkey * `}
64 CMonkey *monkey
= malloc
( sizeof
(CMonkey) );
70 # Object method which will get a callback in wokeUp method, defined in MonkeyActionCallable interface
71 # Must be defined as Nit/C method because of C call inside
72 fun wokeUpAction( toCall: MonkeyActionCallable, message: Object ) is extern import MonkeyActionCallable.wokeUp `{
74 // Allocating memory to keep reference of received parameters
:
77 MonkeyAction *data
= malloc
( sizeof
(MonkeyAction) );
79 // Incrementing reference counter to prevent from releasing
80 MonkeyActionCallable_incr_ref( toCall
);
81 Object_incr_ref( message
);
83 data-
>toCall
= toCall
;
84 data-
>message
= message
;
86 // Calling method which reproduce a callback by passing
:
88 // - Function pointer to object
return method
90 cbMonkey
( recv
, &nit_monkey_callback_func
, data
);