You can pass JavaScript functions to C functions as callbacks. ffi-rs creates a threadsafe_function from the JS function, meaning the JS function will be called asynchronously and the Node.js process will not automatically exit.
To manage memory correctly for these callbacks, it is recommended to use createPointer to create the function pointer for manual memory management, and use freePointer to release the function memory when it is no longer needed.
const testFunction = () => {
const func = (a, b, c, d, e, f, g) => {
// ... callback logic ...
// Release function memory when no longer in use
freePointer({
paramsType: [
funcConstructor({
paramsType: [
DataType.I32,
DataType.Boolean,
DataType.String,
DataType.Double,
arrayConstructor({ type: DataType.StringArray, length: 2 }),
arrayConstructor({ type: DataType.I32Array, length: 3 }),
personType,
],
retType: DataType.Void,
})
],
paramsValue: funcExternal
})
};
// Recommended: use createPointer for manual memory management
const funcExternal = createPointer({
paramsType: [
funcConstructor({
paramsType: [
DataType.I32,
DataType.Boolean,
DataType.String,
DataType.Double,
arrayConstructor({ type: DataType.StringArray, length: 2 }),
arrayConstructor({ type: DataType.I32Array, length: 3 }),
personType,
],
retType: DataType.Void,
})
],
paramsValue: [func]
});
load({
library: "libsum",
funcName: "callFunction",
retType: DataType.Void,
paramsType: [DataType.External],
paramsValue: unwrapPointer(funcExternal),
});
}