Skip to content

Foreign Function Interface

IsaacShelton edited this page Mar 21, 2022 · 1 revision

Foreign Function Interface

Functions from other programming languages can be called via the foreign function interface

Linking to Foreign Object/Archive Files

Object/Archive files can be linked against by using either -l<library>, foreign "<library>.a", or foreign "<library>" library

adept -lglfw
foreign 'windows_libgdi32.a'
foreign 'glfw' library

See command-line usage for more information on -l

Linking to Foreign Shared Libraries

Shared libraries can be linked against by using either -l<shared library>, foreign "<shared library>.dll", or foreign "<shared library>" library

adept -lglfw
foreign 'LLVM.dylib'
foreign 'glfw' library

See command-line usage for more information on -l

Linking to MacOS Frameworks

MacOS frameworks can be linked against by using foreign "<framework>" framework

foreign 'Foundation' framework

Declaring Foreign Functions

Foreign functions can be declared with the foreign keyword, followed by a list of argument types and a return type

foreign glfwCreateWindow(int, int, *ubyte, *GLFWmonitor, *GLFWwindow) *GLFWwindow
stdcall foreign GetProcAddress(ptr, *ubyte) ptr

FFI Example

foreign 'libhello.a'

struct person_t (firstname, lastname *ubyte)

foreign greet(*person_t) void

func main {
    isaac person_t = undef
    isaac.firstname = 'Isaac'
    isaac.lastname = 'Shelton'
    
    greet(&isaac)
}

where libhello.a contains hello.c:

#include <stdio.h>

typedef struct {
    char *firstname;
    char *lastname;
} person_t;

void greet(person_t *person){
    printf("Hello %s %s!\n", person.firstname, person.lastname);
}
Clone this wiki locally