1 # This file is part of NIT (http://www.nitlanguage.org).
3 # Copyright 2014 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 # Utilities and performant structure for the FFI with C
20 intrude import standard
::collection
::array
22 # A thin wrapper around a `NativeCArray` adding length information
23 abstract class CArray[E
]
24 super AbstractArrayRead[E
]
26 private init(length
: Int) do self._length
= length
29 # A native C array, as in a pointer to the first element of the array
30 extern class NativeCArray `{ void * `}
31 type E: nullable Object
33 fun [](index: E): E is abstract
34 fun []=(index: E, val: E) is abstract
36 # Return pointer to the address to the second element of this array
38 # This is the standard `+` operator on pointers in C
39 fun +(offset: Int): SELF is abstract
42 # Wrapper around an array of `int
` in C (`int
*`) with length and destroy state
46 var native_array: NativeCIntArray
49 native_array = new NativeCIntArray(size)
56 assert index >= 0 and index < length
57 return native_array[index]
60 fun []=(index: Int, val: Int)
63 assert index >= 0 and index < length
64 native_array[index] = val
70 if destroyed then return
77 # An array of `int
` in C (`int
*`)
78 extern class NativeCIntArray `{ int* `}
82 new(size
: Int) `{ return calloc(size, sizeof(int)); `}
83 redef fun [](index) `{ return recv[index]; `}
84 redef fun []=(index
, val
) `{ recv[index] = val; `}
86 redef fun +(offset) `{ return recv + offset; `}
89 redef class NativeString
93 redef fun +(offset
) `{ return recv + offset; `}