-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
box.cr
36 lines (32 loc) · 1.01 KB
/
box.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# A Box allows turning any object to a `Void*` and back.
#
# A Box's purpose is passing data to C as a `Void*` and then converting that
# back to the original data type.
#
# For an example usage, see `Proc`'s explanation about sending Procs to C.
class Box(T)
# Returns the original object
getter object : T
# Creates a `Box` with the given object.
#
# This method isn't usually used directly. Instead, `Box.box` is used.
def initialize(@object : T)
end
# Creates a Box for a reference type (or `nil`) and returns the same pointer (or `NULL`)
def self.box(r : Reference?) : Void*
r.as(Void*)
end
# Creates a Box for an object and returns it as a `Void*`.
def self.box(object) : Void*
new(object).as(Void*)
end
# Unboxes a `Void*` into an object of type `T`. Note that for this you must
# specify T: `Box(T).unbox(data)`.
def self.unbox(pointer : Void*) : T
{% if T <= Reference || T == Nil %}
pointer.as(T)
{% else %}
pointer.as(self).object
{% end %}
end
end