Atom

Native extension modules

A native extension includes atom_extension.h and exports atom_extension_v1 using ATOM_EXTENSION_EXPORT. ffi.extension(path) opens the library, invokes initialization and returns a library handle for its registered members. The ABI version is ATOM_EXTENSION_ABI (1).

The initializer receives an AtomExtension with api, vm, an opaque registry context, function(context, name, AtomNative, function_context) and value(context, name, AtomValue). Return the registration status. The supplied extension and registry context are valid for initialization. Registered callbacks may retain the API table, whose fields are version, error, string, string_bytes, array, dict, get, set, append and call. Their callback signatures and behavior correspond to the embedding functions below. Use that table to avoid linking a separate Atom runtime into the extension. Keep the loaded extension live while its code is in use.

Save as extension.c and compile with the SDK include directory. Linux uses cc -std=c17 -shared -fPIC -I atom-sdk/include extension.c -o greeting.so. On macOS use -dynamiclib and greeting.dylib. On MinGW use -shared and greeting.dll.

extension.c
#include <atom_extension.h>

static AtomStatus greet(AtomVM *vm, void *context, size_t argc,
                        const AtomValue *argv, AtomValue *result)
{
    const AtomExtensionAPI *api = context;
    (void)argv;
    if (argc != 0) return api->error(vm, "greet takes no arguments");
    return api->string("Hello from C", 12, result);
}

ATOM_EXTENSION_EXPORT AtomStatus atom_extension_v1(const AtomExtension *extension)
{
    if (extension->api->version != ATOM_EXTENSION_ABI) return ATOM_RUNTIME_ERROR;
    return extension->function(extension->context, "greet", greet,
                               (void *)extension->api);
}

Save as extension.atom. Run atom run extension.atom -- ./greeting.so or give the corresponding platform filename.

extension.atom
use ffi
use os

library = ffi.extension(os.args[0])
try:
    assert(library.greet() == 'Hello from C')
finally:
    ffi.close(library)