class FFI::Pointer

Public Instance Methods

read_array_of_string() click to toggle source

Returns an array of strings for char** types.

# File lib/ffi/win32/extensions.rb, line 6
def read_array_of_string
  elements = []

  loc = self

  until (element = loc.read_pointer).null?
    elements << element.read_string
    loc += FFI::Type::POINTER.size
  end

  elements
end
read_utf16string() click to toggle source
# File lib/ffi/win32/extensions.rb, line 58
def read_utf16string
  offset = 0
  offset += 2 while get_bytes(offset, 2) != "\x00\x00"
  get_bytes(0, offset).force_encoding("utf-16le").encode("utf-8")
end
read_wide_string(num_bytes = size) click to toggle source

Read num_bytes from a wide character string pointer. If this fails (typically because there are only null characters) then an empty string is returned instead.

# File lib/ffi/win32/extensions.rb, line 23
def read_wide_string(num_bytes = size)
  read_bytes(num_bytes).force_encoding("UTF-16LE")
    .encode("UTF-8", invalid: :replace, undef: :replace)
    .split(0.chr).first.force_encoding(Encoding.default_external)
rescue
  ""
end
read_wstring(num_wchars = nil) click to toggle source

Read null-terminated Unicode strings.

# File lib/ffi/win32/extensions.rb, line 33
def read_wstring(num_wchars = nil)
  if num_wchars.nil?
    # Find the length of the string
    length = 0
    last_char = nil
    while last_char != "\000\000"
      length += 1
      last_char = get_bytes(0, length * 2)[-2..-1]
    end

    num_wchars = length
  end

  wide_to_utf8(get_bytes(0, num_wchars * 2))
end
wide_to_utf8(wstring) click to toggle source
# File lib/ffi/win32/extensions.rb, line 49
def wide_to_utf8(wstring)
  # ensure it is actually UTF-16LE
  # Ruby likes to mark binary data as ASCII-8BIT
  wstring = wstring.force_encoding("UTF-16LE")

  # encode it all as UTF-8 and remove trailing CRLF and NULL characters
  wstring.encode("UTF-8").strip
end