Low-Level Programming and C Bindings

Unlike Ruby, Crystal has a lot of features that make it useful for embedded and IoT applications. For example, you can work with pointers of any type, as you see here:

 ptr = Pointer(UInt8).​malloc​(20) ​# malloc allocates memory
 ptr.​value​ = 42_u8 ​# 42 here is of type u8
 ptr ​# => Pointer(UInt8)@0x271dfe0
 ptr.​value​ ​# => 42
 ptr.​class​ ​# => Pointer(UInt8)
 
 # Converting between pointer types with as:
 # Int8* is the same as Pointer(Int8)
 ptr.​as​(Int8*) ​# => Pointer(Int8)@0x271dfe0
 
 n = 42
 ptr_n = pointerof(n)
 ptr_n.​value​ = 108
 n ​# => 108

A pointer does no checks at all: such code is regarded as unsafe, which means that memory corruption, segmentation ...

Get Programming Crystal now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.