How to Garbage Collect a callback function when using node-ffi?

Viewed 23

How do you collect a ffi callback right after the callback has been executed?.

This is an example code that mostly works, except it needs a window handle and a message to send. Here I am using Win32 to get the callback message, so all the definitions here have to do with the win32 api.

const ffi = require('ffi-napi')
const ref = require('ref-napi');
var winterface = {}
var wintypes = {};
wintypes.BOOL = ref.types.int;
wintypes.HANDLE = ref.types.uint64;
wintypes.HWND = wintypes.HANDLE;
wintypes.UINT = ref.types.uint;
wintypes.ULONG_PTR = ref.types.uint64;
wintypes.UINT_PTR = wintypes.ULONG_PTR;
wintypes.WPARAM = wintypes.UINT_PTR;
wintypes.LONG_PTR = ref.types.int64;
wintypes.LPARAM = wintypes.LONG_PTR;
wintypes.WPARAM, wintypes.LPARAM;
wintypes.VOID = ref.types.void;
wintypes.SENDASYNCPROC = ref.refType(wintypes.VOID)
wintypes.LRESULT = wintypes.LONG_PTR;
winterface.User32 = {
  SendMessageCallbackA: [wintypes.BOOL, [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM, wintypes.SENDASYNCPROC, wintypes.ULONG_PTR]]
};
let user32 = ffi.Library("User32.dll", winterface.User32);
(function(hWnd, WM) {
  var callback = ffi.Callback(wintypes.VOID, [wintypes.HWND, wintypes.UINT, wintypes.ULONG_PTR, wintypes.LRESULT], () => {
    //callback has probably been already garbage collected.
    //I want to keep it and garbage collect it right after the callback has been executed
  })

  user32.SendMessageCallbackA(hWnd, WM, 0, 0, callback, 0)

})(hWnd, WM_FOO); //pretend hWnd is a valid handle and WM_FOO is a valid message;

since callback is not stored by SendMessageCallbackA it will get garbage collected meaning it will never execute. But if I save it in a global variable, it will never garbage collect.. How would you solve this problem?

0 Answers
Related