如何使用ffi将WinApi函数加载到Node.js中?

3

有一个名为 ffi 的库,它承诺允许用户加载系统本地库并调用其中的函数。

使用他们的示例,我尝试使用 User32.dll 中的 MessageBox 函数:

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);

这个出现了错误:

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)

我试图将声明更改为一些无意义的内容,但是我得到了相同的错误,所以我猜它确实是错误的。我该如何修复它以使其正常工作?我是否指定了不正确的数据类型?


路径到 "user32.dll" 是否正确? - guest271314
我对你使用CString来处理LPCWSTR感到怀疑,我认为"指针"可能是正确的选择。此外,在函数名上,你可能需要使用别名MessageBoxW。http://opendirective.net/blog/2015/10/working-with-windows-native-code-from-node-js/ - Tim
1个回答

0

试试这个。

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

从技术上讲,这些是LPCSTR字符串而不是LPCWSTR,因为我们使用的是Ansi而不是UTF-16


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接