【问题标题】:Ruby FFI: Pointer to an array of unsigned integerRuby FFI:指向无符号整数数组的指针
【发布时间】:2014-05-12 08:49:24
【问题描述】:

我正在尝试在我的 ruby​​ 程序中使用 EnumProcesses

BOOL WINAPI EnumProcesses(
  _Out_  DWORD *pProcessIds,
  _In_   DWORD cb,
  _Out_  DWORD *pBytesReturned
);

我需要定义一个指向无符号整数数组的指针,我这样做的方式如下:

require 'ffi'

module Win32
  extend FFI::Library
  ffi_lib 'Psapi'
  ffi_convention :stdcall
  attach_function :EnumProcesses,  [:pointer, :uint, :pointer], :int
end

process_ids    = FFI::MemoryPointer.new(:uint, 1024)
bytes_returned = FFI::MemoryPointer.new(:uint)

if Win32.EnumProcesses(process_ids, process_ids.size, bytes_returned) != 0
  puts bytes_returned.read_string
end

上面返回的字节的输出是一种像x☺这样的垃圾字符

让我知道我哪里做错了?

【问题讨论】:

    标签: c ruby winapi process ffi


    【解决方案1】:

    你们很亲密。主要问题是解释从 Microsoft 返回的数据。它不是一个字符串。它是一个 DWORD 或 uint32 数组。

    试一试:

    require 'ffi'
    
    module Win32
    
      extend FFI::Library
      ffi_lib 'Psapi'
      ffi_convention :stdcall
    
    =begin
      BOOL WINAPI EnumProcesses(
        _Out_  DWORD *pProcessIds,
        _In_   DWORD cb,
        _Out_  DWORD *pBytesReturned
      );
    =end
      attach_function :EnumProcesses, [:pointer, :uint32, :pointer], :int
    
    end
    
    # Allocate room for the windows process ids.
    process_ids = FFI::MemoryPointer.new(:uint32, 1024)
    
    # Allocate room for windows to tell us how many process ids there were.
    bytes_returned = FFI::MemoryPointer.new(:uint32)
    
    # Ask for the process ids
    if Win32.EnumProcesses(process_ids, process_ids.size, bytes_returned) != 0
    
      # Determine the number of ids we were given
      process_ids_returned = bytes_returned.read_int / bytes_returned.size
    
      # Pull all the ids out of the raw memory and into a local ruby array.
      ids = process_ids.read_array_of_type(:uint32, :read_uint32, process_ids_returned)
    
      puts ids.sort
    end
    

    【讨论】:

      猜你喜欢
      • 2012-01-24
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      相关资源
      最近更新 更多