linkSymbols

Bun

Symbol

linkSymbols

function linkSymbols<Fns extends Record<string, FFIFunction>>(): Library<Fns>;

Link a map of symbols to JavaScript functions

This lets you use native libraries that were already loaded somehow. You usually will want dlopen instead.

You could use this with Node-API to skip loading a second time.

@param symbols

Map of symbols to load where the key is the symbol name and the value is the FFIFunction

import { linkSymbols } from "bun:ffi";

const [majorPtr, minorPtr, patchPtr] = getVersionPtrs();

const lib = linkSymbols({
  // Unlike with dlopen(), the names here can be whatever you want
  getMajor: {
    returns: "cstring",
    args: [],

    // Since this doesn't use dlsym(), you have to provide a valid ptr
    // That ptr could be a number or a bigint
    // An invalid pointer will crash your program.
    ptr: majorPtr,
  },
  getMinor: {
    returns: "cstring",
    args: [],
    ptr: minorPtr,
  },
  getPatch: {
    returns: "cstring",
    args: [],
    ptr: patchPtr,
  },
});

const [major, minor, patch] = [
  lib.symbols.getMajor(),
  lib.symbols.getMinor(),
  lib.symbols.getPatch(),
];

This is powered by just-in-time compiling C wrappers that convert JavaScript types to C types and back. Internally, bun uses tinycc, so a big thanks goes to Fabrice Bellard and TinyCC maintainers for making this possible.

Referenced types

interface Library<Fns extends Symbols>

  • close(): void;

    dlclose the library, unloading the symbols and freeing allocated memory.

    Once called, the library is no longer usable.

    Calling a function from a library that has been closed is undefined behavior.