How to load WinApi functions into Node.js using ffi?

Viewed 2407

There's a library called ffi that promises to allow user to load system native libraries and call functions found in them.

Using their examples I tried to use MessageBox function located in User32.dll:

var ref = require('ref');
var ffi = require('ffi');
var Struct = require('ref-struct');

// Define Winapi types according to 
//  https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx
var winapi = {};
winapi.void = ref.types.void;
winapi.PVOID = ref.refType(winapi.void);
winapi.HANDLE = winapi.PVOID;
winapi.HWND = winapi.HANDLE;
winapi.WCHAR = ref.types.char;
winapi.LPCWSTR = ref.types.CString;
winapi.UINT = ref.types.uint;

// Try to load message box function as defined in 
//   https://msdn.microsoft.com/en-us/library/windows/desktop/ms645505%28v=vs.85%29.aspx
var current = ffi.Library("user32.dll", {
  'MessageBox': [ 'int', [ winapi.HWND, winapi.LPCWSTR, winapi.LPCWSTR, winapi.UINT ] ]
});
current.MessageBox(0, "sss", "sss", 0);

This has failed with an error:

C:\MYSELF\programing\nodejs\node_modules\ffi\lib\dynamic_library.js:112
    throw new Error('Dynamic Symbol Retrieval Error: ' + this.error())
          ^
Error: Dynamic Symbol Retrieval Error: Win32 error 127
    at DynamicLibrary.get (C:\MYSELF\programing\nodejs\node_modules\ffi\lib\dynamic_library.js:112:11)
    at C:\MYSELF\programing\nodejs\node_modules\ffi\lib\library.js:50:19
    at Array.forEach (native)
    at Object.Library (C:\MYSELF\programing\nodejs\node_modules\ffi\lib\library.js:47:28)
    at Object.<anonymous> (C:\MYSELF\programing\nodejs\ffitest\winapi.js:23:19)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)

I tried to change declaration to some nonsense and I got the same error, so I guess it really is wrong. How do I fix it to have it work correctly? Did I specify incorrect data types?

1 Answers

try this instead.

var current = ffi.Library("User32.dll", {
   'MessageBoxA': [ 'int', [ winapi.HWND, winapi.LPCWSTR, winapi.LPCWSTR, winapi.UINT ] ]}
);
current.MessageBoxA(ref.NULL, "sss", "sss", 0);

Technically, these are LPCSTR strings not LPCWSTR since we're using Ansi, not UTF-16

Related