FFI and Embedding – Combining Rust and Other Languages

Up until this point in the book, we've discussed Rust more or less in isolation. Rust was intentionally designed to integrate with other programming languages by calling external programming languages through its Foreign Function Interface (FFI) and by being embedded itself. Many modern programming languages offer FFI, easy embedding, or both. Python, for instance, can very conveniently call out to libraries with C calling conventions and can be embedded with a little forethought. Lua, a high-level and garbage-collected language like Python, has a convenient FFI and can be embedded without much trouble. Erlang has a small handful of FFI interfaces but Erlang is not, itself, easily embedded into user-space environments. Amusingly, it's fairly straightforward to compile Erlang into an RTOS image.

In this chapter, we'll discuss calling out to foreign code in Rust and embedding Rust into foreign programming languages. We'll start off by extending the corewars evolver program —feruscore—that we covered at the tail end of Chapter 8, High-Level Parallelism – Threadpools, Parallel Iterators, and Processes. You are encouraged to read that material before starting this chapter. After we've extended feruscore by embedding a C MARS simulator inside it, we'll move on to calling Rust functions from a C program. We'll demonstrate embedding Lua into a Rust system for convenient scripting and close the chapter by embedding Rust in high-level garbage-collected languages—Python and Erlang.

By the end of this chapter, we will have:

  • Adapted the feruscore project from the last section to incorporate a C simulator
  • Demonstrated the inclusion of Lua code into a Rust project
  • Demonstrated the inclusion of Rust code into a C project
  • Demonstrated the inclusion of Rust code into a Python project
  • Demonstrated the inclusion of Rust code into an Erlang/Elixir project
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.7.240