0

我正在尝试使用 node-ffi 与 win32 api FormatMessageA 进行交互,但是我似乎无法获取 out lpBuffer 参数,这是一段代码来显示我尝试过的内容

   'use strict';

   const ref = require('ref');
   const ffi = require('ffi');

   const Kernel32 = ffi.Library('Kernel32.dll', {
       FormatMessageA: ['ulong', [
           'ulong', //flags 
           'void *', 
           'ulong', //status number
           'ulong', //language 
           'uchar *',
           'ulong',
           'void *'
       ]]
   });


   const FORMAT_MESSAGE_FROM_SYSTEM = 0x1000;
   const FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x100;
   const FORMAT_MESSAGE_IGNORE_INSERTS = 0x200;

   const lpBuffer = ref.alloc('uchar *'); 

   const result = Kernel32.FormatMessageA(
       FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
       null, 
       0x80090300, //error code
       0,
       lpBuffer,
       0, 
       null
   );

   console.log(result); //prints 57 bytes

我知道函数是成功的,因为它返回 57 但是我无法获得包含我需要的错误字符串的 lpBuffer 值。

4

1 回答 1

1

正如我在第一评论中所说,根据[MSDN]FormatMessage功能

  • FORMAT_MESSAGE_ALLOCATE_BUFFER描述:

    lpBuffer参数是一个指向; LPTSTR您必须将指针强制转换为LPTSTR(例如,(LPTSTR)&lpBuffer).

  • 页面底部的(2 nd ) 示例:

    // Some code (not relevant for this problem)
    LPWSTR pBuffer = NULL;
    // Some more code (still not relevant)
    FormatMessage(FORMAT_MESSAGE_FROM_STRING |
                  FORMAT_MESSAGE_ALLOCATE_BUFFER,
                  pMessage, 
                  0,
                  0,
                  (LPWSTR)&pBuffer,
    // The rest of the code (not relevant)
    

dwFlags参数由 组成时FORMAT_MESSAGE_ALLOCATE_BUFFER,函数期望lpBuffer参数是LPTSTR(指向TCHAR),实际上是指向LPTSTR(双指针TCHAR)的指针LPTSTR

那,用JS翻译(我没有经验)意味着:

const lpBuffer = ref.alloc('uchar **');

注意:根据同一页面,缓冲区应该在LocalFree不再需要时被释放(这是有道理的,因为FormatMessage为它分配内存 - 这就是它需要双指针的原因)。同样,不知道这将如何在JS中翻译(我所知道的是LocalFree应该在uchar *(取消引用的)缓冲区上调用,而不是直接在lpBuffer.

于 2017-03-24T19:44:33.783 回答