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 relay
18 # native callbacks from C to a Nit program.
19 module callback_monkey
31 MonkeyActionCallable toCall;
37 // Method which reproduce a callback answer
38 // Please note that a function pointer is only used to reproduce the callback
39 void cbMonkey(CMonkey *mkey, void callbackFunc(CMonkey*, MonkeyAction*), MonkeyAction *data)
42 callbackFunc(mkey, data);
45 // Back of background treatment, will be redirected to callback function
46 void nit_monkey_callback_func(CMonkey *mkey, MonkeyAction *data)
48 // To call a your method, the signature must be written like this:
49 // <Interface Name>_<Method>...
50 MonkeyActionCallable_woke_up(data->toCall, mkey, data->message);
54 # Implementable interface to get callback in defined methods
55 interface MonkeyActionCallable
56 fun woke_up
(sender
:Monkey, message
: Object) is abstract
59 # Defining my object type Monkey, which is, in a low level, a pointer to a C struct (CMonkey)
60 extern class Monkey `{ CMonkey * `}
63 CMonkey *monkey
= malloc
(sizeof
(CMonkey));
69 # Object method which will get a callback in woke_up method, defined in MonkeyActionCallable interface
70 # Must be defined as Nit/C method because of C call inside
71 fun woke_up_action(toCall: MonkeyActionCallable, message: Object) is extern import MonkeyActionCallable.woke_up `{
73 // Allocating memory to keep reference of received parameters
:
76 MonkeyAction *data
= malloc
(sizeof
(MonkeyAction));
78 // Incrementing reference counter to prevent from releasing
79 MonkeyActionCallable_incr_ref(toCall
);
80 Object_incr_ref(message
);
82 data-
>toCall
= toCall
;
83 data-
>message
= message
;
85 // Calling method which reproduce a callback by passing
:
87 // - Function pointer to object
return method
89 cbMonkey
(self, &nit_monkey_callback_func
, data
);