Crystal For Rubyists
  • Know Ruby? Enter Crystal!
  • book
    • Chapter 1: Why Crystal?
    • Chapter 2: Installing Crystal
    • Chapter 3: Writing Your First Crystal Program
    • Chapter 4: Creating a new project
    • Chapter 5: Testing
    • Chapter 6: FizzBuzz
    • Chapter 7: Types and Method Overloading
    • Chapter 8: Concurrency and Channels
    • Chapter 9: Macros and Metaprogramming
    • Chapter 10: C Bindings
Powered by GitBook
On this page
  1. book

Chapter 10: C Bindings

There are lots of useful C libraries out there. It’s important that we make use of them instead of rewriting every single of them.

In Crystal, It’s super easy to use existing C libraries with bindings. Even Crystal itself uses C libraries.

For example Crystal uses libpcre for it’s Regex implementation.

Like I said it’s super easy to write bindings for C. Crystal itself links to libpcre like this

@[Link("pcre")]
lib LibPCRE
...
end

With just 3 lines of code you we’re linked to libpcre :) We use lib keyword to group functions and types that belong to a library. And it’s a good convetion to start with Lib for your C library declarations.

Next we bind to C functions with the fun keyword.

@[Link("pcre")]
lib LibPCRE
  type Pcre = Void*
  fun compile = pcre_compile(pattern : UInt8*, options : Int, errptr : UInt8**, erroffset : Int*, tableptr : Void*) : Pcre
end

Here we binded to libpcres compile function with the matching types. Now we can easily access this function in our Crystal code.

LibPCRE.compile(..)
PreviousChapter 9: Macros and Metaprogramming

Last updated 6 years ago