1

ruby ffiを使用して、関数をアタッチする共有オブジェクト lib があります。各関数にエイリアスを付けて、エイリアスを非公開にしたいのは、それらを呼び出すと危険な場合があるためです。各関数を独自の 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

クラス << self の外側に attach_function を配置し、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 に答える