function

ffi.linkSymbols

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

Link a map of symbols to JavaScript functions

Use this for native libraries that are already loaded, for example by Node-API, to skip loading them a second time. You usually want dlopen instead.

@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(),
];

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.