Turn a native library's function pointer into a JavaScript function
Libraries using Node-API & bun:ffi in the same module could use this to skip an extra dlopen() step.
Symbol
Turn a native library's function pointer into a JavaScript function
Libraries using Node-API & bun:ffi in the same module could use this to skip an extra dlopen() step.
FFIFunction declaration. ptr
is required
import {CFunction} from 'bun:ffi';
const getVersion = new CFunction({
returns: "cstring",
args: [],
ptr: myNativeLibraryGetVersion,
});
getVersion();
getVersion.close();
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.
Arguments to a FFI function (C ABI)
Defaults to an empty array, which means no arguments.
To pass a pointer, use "ptr" or "pointer" as the type name. To get a pointer, see ptr.
From JavaScript:
import { dlopen, FFIType, suffix } from "bun:ffi"
const lib = dlopen(`adder.${suffix}`, {
add: {
// FFIType can be used or you can pass string labels.
args: [FFIType.i32, "i32"],
returns: "i32",
},
})
lib.symbols.add(1, 2)
In C:
int add(int a, int b) {
return a + b;
}
Return type to a FFI function (C ABI)
Defaults to FFIType.void
To pass a pointer, use "ptr" or "pointer" as the type name. To get a pointer, see ptr.
From JavaScript:
import { dlopen, CString } from "bun:ffi"
const lib = dlopen('z', {
version: {
returns: "ptr",
}
});
console.log(new CString(lib.symbols.version()));
In C:
char* version()
{
return "1.0.0";
}
Can C/FFI code call this function from a separate thread?
Only supported with JSCallback.
This does not make the function run in a separate thread. It is still up to the application/library to run their code in a separate thread.
By default, JSCallback calls are not thread-safe. Turning this on incurs a small performance penalty for every function call. That small performance penalty needs to be less than the performance gain from running the function in a separate thread.