1

我有一个使用 ruby​​ ffi附加函数的共享对象库。我想为每个函数附加一个别名并将别名设为私有,因为调用它们可能很危险。我将每个函数包装在它们自己的 ruby​​ 模块函数中,这是一个简单的示例:

module LibC
    extend FFI::Library

    ffi_lib FFI::Library::LIBC

    attach_function :free, [:pointer], :void
end

module MyModule
    class << self
        extend FFI::Library

        ffi_lib '../my_shared_lib.so'

        def function(str)
            is_string(str)
            ptr = ffi_function(str)
            result = String.new(ptr.read_string)
            LibC.free(ptr)

            result
        end

        private
        # attach function
        attach_function :ffi_function, :function, [:string], :pointer

        def is_string(object)
             unless object.kind_of? String
                 raise TypeError,
                     "Wrong argument type #{object.class} (expected String)"
             end
        end
    end
end

该函数ffi_function似乎仍然可以在模块外部调用。我怎样才能让它完全私有化?

4

1 回答 1

0

将 attach_function 放在 class << self 之外,并在 self 中添加一个 private :ffi_function。

这是一个改编自其他代码的示例。EnumProcesses 是隐藏的 ffi_function,而 process_ids 是公共包装器。

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

  class << self

    def process_ids
      # Allocate room for the windows process ids.
      windows_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 EnumProcesses(windows_process_ids, windows_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.
        windows_process_ids.read_array_of_type(:uint32, :read_uint32, process_ids_returned)
      end

    end

    # Hide EnumProcesses from the outside
    private :EnumProcesses
  end

end

Win32.process_ids # This will work
Win32.EnumProcesses # This throws an exception: private method `EnumProcesses' called for Win32:Module (NoMethodError)
于 2014-08-31T19:19:59.433 回答