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
32 type SELF: NativeCArray
34 fun [](index: E): E is abstract
35 fun []=(index: E, val: E) is abstract
37 # Return pointer to the address to the second element of this array
39 # This is the standard `+` operator on pointers in C
40 fun +(offset: Int): SELF is abstract
43 # Wrapper around an array of `int
` in C (`int
*`) with length and destroy state
47 var native_array: NativeCIntArray
50 native_array = new NativeCIntArray(size)
57 assert index >= 0 and index < length
58 return native_array[index]
61 fun []=(index: Int, val: Int)
64 assert index >= 0 and index < length
65 native_array[index] = val
71 if destroyed then return
78 # An array of `int
` in C (`int
*`)
79 extern class NativeCIntArray `{ int* `}
82 redef type SELF: NativeCIntArray
84 new(size
: Int) `{ return calloc(size, sizeof(int)); `}
85 redef fun [](index) `{ return recv[index]; `}
86 redef fun []=(index
, val
) `{ recv[index] = val; `}
88 redef fun +(offset) `{ return recv + offset; `}
91 redef class NativeString
94 redef type SELF: NativeString
96 redef fun +(offset
) `{ return recv + offset; `}