0
# Scala Native nativelib
1
2
Scala Native nativelib is the core native interoperability library for Scala Native, providing comprehensive facilities for unsafe operations, memory management, and C-style data types. It enables Scala programs compiled to native code to interface directly with C/C++ libraries, system calls, and low-level memory operations while maintaining type safety where possible.
3
4
## Package Information
5
6
- **Package Name**: org.scala-native:nativelib_native0.5_3
7
- **Package Type**: maven
8
- **Language**: Scala
9
- **Installation**: Add to `build.sbt`: `libraryDependencies += "org.scala-native" %%% "nativelib" % "0.5.7"`
10
11
## Core Imports
12
13
```scala
14
import scala.scalanative.unsafe._
15
import scala.scalanative.unsigned._
16
import scala.scalanative.runtime._
17
```
18
19
Individual package imports:
20
```scala
21
import scala.scalanative.unsafe.{Zone, Ptr, CString, CInt}
22
import scala.scalanative.unsigned.{UInt, ULong}
23
import scala.scalanative.runtime.{Array => NativeArray}
24
```
25
26
## Basic Usage
27
28
```scala
29
import scala.scalanative.unsafe._
30
import scala.scalanative.unsigned._
31
32
// Memory allocation with automatic cleanup
33
Zone.acquire { implicit z =>
34
// Allocate a C string
35
val cstr: CString = toCString("Hello, Native World!")
36
37
// Convert back to Scala string
38
val scalaStr: String = fromCString(cstr)
39
40
// Allocate typed memory
41
val intPtr: Ptr[CInt] = alloc[CInt](10) // allocate 10 integers
42
intPtr(0) = 42 // set first element
43
val value: CInt = intPtr(0) // read first element
44
45
// Work with unsigned integers
46
val unsigned: UInt = 42.toUInt
47
val result: UInt = unsigned + 10.toUInt
48
}
49
```
50
51
## Architecture
52
53
Scala Native nativelib is organized around several core concepts:
54
55
- **Memory Management**: Zone-based allocation provides automatic memory cleanup and leak prevention
56
- **Type Safety**: Strong typing through `Ptr[T]`, `Tag[T]`, and sized types while allowing unsafe operations when needed
57
- **C Interoperability**: Direct mapping between Scala and C types with zero-cost abstractions
58
- **Unsigned Arithmetic**: Full unsigned integer support with proper overflow semantics
59
- **Native Arrays**: High-performance array types optimized for native code generation
60
- **Function Pointers**: Type-safe function pointer interface for callbacks and native function calls
61
62
## Capabilities
63
64
### Memory Management and Pointers
65
66
Core pointer operations, memory allocation, zone-based memory management, type-safe memory operations with the Tag system, and low-level runtime intrinsics for performance-critical code.
67
68
```scala { .api }
69
trait Zone {
70
def alloc(size: CSize): Ptr[Byte]
71
def close(): Unit
72
def isClosed: Boolean
73
}
74
75
object Zone {
76
def acquire[T](f: Zone => T): T
77
def open(): Zone
78
}
79
80
final class Ptr[T] {
81
def unary_!(implicit tag: Tag[T]): T
82
def unary_!_=(value: T)(implicit tag: Tag[T]): Unit
83
def +(offset: Int)(implicit tag: Tag[T]): Ptr[T]
84
def -(offset: Int)(implicit tag: Tag[T]): Ptr[T]
85
def apply(offset: Int)(implicit tag: Tag[T]): T
86
def update(offset: Int, value: T)(implicit tag: Tag[T]): Unit
87
}
88
```
89
90
[Memory Management](./memory-management.md)
91
92
### C Data Types and Interoperability
93
94
Comprehensive C type system including primitive types, strings, arrays, complete CStruct0-22 structure families, complete CFuncPtr0-22 function pointer families, and variadic arguments for seamless C library integration.
95
96
```scala { .api }
97
// C type aliases
98
type CInt = Int
99
type CString = Ptr[CChar]
100
type CChar = Byte
101
type CSize = USize
102
103
// String conversions
104
def fromCString(cstr: CString, charset: Charset = Charset.defaultCharset()): String
105
def toCString(str: String)(implicit z: Zone): CString
106
def toCString(str: String, charset: Charset)(implicit z: Zone): CString
107
108
// C arrays and structures
109
final class CArray[T, N <: Nat] {
110
def length(implicit tag: Tag[N]): Int
111
def apply(idx: Int)(implicit tag: Tag[T]): T
112
def update(idx: Int, value: T)(implicit tag: Tag[T]): Unit
113
def at(idx: Int)(implicit tag: Tag[T]): Ptr[T]
114
}
115
116
// Function pointers (0-22 arity)
117
abstract class CFuncPtr0[R] {
118
def apply(): R
119
}
120
abstract class CFuncPtr1[T1, R] {
121
def apply(arg1: T1): R
122
}
123
```
124
125
[C Interoperability](./c-interop.md)
126
127
### Unsigned Integer Types
128
129
Full-featured unsigned integer arithmetic with proper overflow semantics and conversions for systems programming.
130
131
```scala { .api }
132
final class UByte extends AnyVal {
133
def +(other: UByte): UByte
134
def -(other: UByte): UByte
135
def *(other: UByte): UByte
136
def /(other: UByte): UByte
137
def %(other: UByte): UByte
138
def &(other: UByte): UByte
139
def |(other: UByte): UByte
140
def ^(other: UByte): UByte
141
def <<(shift: Int): UByte
142
def >>(shift: Int): UByte
143
def >>>(shift: Int): UByte
144
}
145
146
// Similar interfaces for UShort, UInt, ULong, USize
147
```
148
149
[Unsigned Types](./unsigned-types.md)
150
151
### Native Arrays and Runtime
152
153
High-performance native array types and comprehensive runtime utilities including complete garbage collector interface, thread management, root set management, runtime information, and system integration.
154
155
```scala { .api }
156
sealed abstract class Array[T] {
157
def length: Int
158
def stride: Int
159
def at(i: Int): Ptr[T]
160
def apply(i: Int): T
161
def update(i: Int, value: T): Unit
162
def clone(): Array[T]
163
}
164
165
// Typed array implementations
166
final class IntArray extends Array[Int]
167
final class FloatArray extends Array[Float]
168
final class ObjectArray[T] extends Array[T]
169
170
// GC interface
171
object GC {
172
def getInitHeapSize(): ULong
173
def getMaxHeapSize(): ULong
174
def getUsedHeapSize(): ULong
175
def collect(): Unit
176
}
177
```
178
179
[Native Arrays and Runtime](./arrays-runtime.md)
180
181
### Annotations and Compiler Directives
182
183
Comprehensive annotation system including optimization control, memory layout, external interface declarations, memory model consistency, reflection support, and development utilities for fine-tuning native code generation and interoperability.
184
185
```scala { .api }
186
class alwaysinline extends scala.annotation.StaticAnnotation
187
class noinline extends scala.annotation.StaticAnnotation
188
class nooptimize extends scala.annotation.StaticAnnotation
189
class align(size: Int, group: String = "") extends scala.annotation.StaticAnnotation
190
class extern extends scala.annotation.StaticAnnotation
191
class blocking extends scala.annotation.StaticAnnotation
192
```
193
194
[Annotations](./annotations.md)
195
196
## Types
197
198
```scala { .api }
199
// Platform-dependent size types
200
type Size = /* Int on 32-bit, Long on 64-bit */
201
type USize = /* UInt on 32-bit, ULong on 64-bit */
202
203
// Tag system for type information
204
trait Tag[T] {
205
def size: Size
206
def load(ptr: Ptr[Byte]): T
207
def store(ptr: Ptr[Byte], value: T): Unit
208
}
209
210
// Natural numbers for array sizes
211
sealed abstract class Nat
212
object Nat {
213
class _0 extends Nat
214
class _1 extends Nat
215
class _2 extends Nat
216
// ... continues to higher numbers
217
}
218
```
219
220
## Safety and Best Practices
221
222
- **Always use Zone.acquire**: Automatic memory management prevents leaks
223
- **Null checks**: C interop may introduce null pointers - check before dereferencing
224
- **Charset handling**: Specify charsets explicitly when converting strings
225
- **Type tags**: Required for generic operations - usually inferred automatically
226
- **Unsigned arithmetic**: Be aware of overflow behavior in unsigned operations
227
- **External annotations**: Use `@extern` and `@blocking` appropriately for native functions