Foreign Function Interface

Type-C provides a Lua-inspired API to interface with the virtual machine. However, since Type-C requires types to interface properly with FFIs, a type annotation is needed by the compiler. In this section we review with some examples, how to define the ffi in the language level and VM level. This requires knowledge of the C programming language. Also the VM API will be presented and used heavily, but it also subject to change as the VM progresses, but the philosophy and approach will always be the same.

Type-V FFI API

Type-V VM api/typev_api.h provides the require functions to interface with the VM. These functions you will be using in your main FFI code, to interface with the VM to get argument, build data structure and return values.

Note as of right now, (and possible not any time soon), you cannot interface with the global state, e.g define global variables, or change the state of global symbols. Also this file is very likely to change.

While you can push dynamic objects into the stack using the _u64 methods, it is not recommended. It is important to use the _ptr operations for pointers, such as structs, classes etc, so that the GC knows the objects in stack are being treated as dynamically allocated symbols and not just regular numbers.

Declaring Type-C FFI Definitions

A simple FFI declaration is done using the keyword extern. Declaring FFIs definitions in type-c must be done at a global level, and ideally in an isolate module. Once the definition has been written, the functions can be accessed using the FFI module name.

Writing FFIs in Type-V

In addition to definitions, the VM will need the actual code. Hence, importing the required api header file and linking the VM is required, to generate your shared object.

Here is an example which is used to manipulate strings

Every FFI needs to define typev_ffi_open with the same signature as the example. The open function will be the first the VM calls to load the methods. Additionally, the order of methods as defined with the array (in the demo case string_lib must be exactly the same order of function definitions in your type-c FFI definition file. Keep in mind that Type-V stores very minimal run-time type information.


Kudos! Keep reading!