Class: FFI::Pointer

Inherits:
Object
  • Object
show all
Defined in:
lib/ffi/extra.rb

Direct Known Subclasses

ExecutableMemoryPointer

Instance Method Summary collapse

Instance Method Details

#read(type, *args) ⇒ Object Also known as: typecast



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/ffi/extra.rb', line 81

def read (type, *args)
	if type.is_a?(Symbol)
		if respond_to? "read_#{type}"
			return send "read_#{type}"
		else
			type = FFI.find_type(type)
		end
	end

	if type.is_a?(Type::Builtin)
		send "read_#{type.name.downcase}", *args
	elsif type.is_a?(Class) && type.ancestors.member?(FFI::Struct) && !type.ancestors.member?(FFI::ManagedStruct)
		type.new(self, *args)
	elsif type.respond_to? :from_native
		type.from_native(typecast(type.native_type, *args), nil)
	else
		raise ArgumentError, 'you have to pass a Struct, a Builtin type or a Symbol'
	end
end

#read_array_of(type, number) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/ffi/extra.rb', line 119

def read_array_of (type, number)
	if type.is_a?(Symbol)
		if respond_to? "read_array_of_#{type.downcase}"
			return send "read_array_of_#{type.downcase}", number
		else
			type = FFI.find_type(type)
		end
	end

	type = type.native_type if type.respond_to? :native_type

	if type.is_a?(Class) && type.ancestors.member?(FFI::Struct)
		read_array_of_pointer(number).map {|pointer|
			type.new(pointer)
		}
	else
		begin
			send "read_array_of_#{type.name.downcase}", number
		rescue NameError
			raise ArgumentError, "#{type.name} is not supported"
		end
	end
end

#write(what, type = nil) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/ffi/extra.rb', line 103

def write (what, type = nil)
	if type
		if respond_to? "write_#{type.downcase}"
			send "write_#{type.downcase}", what
		else
			write_bytes what, what.size
		end
	else
		case what
			when FFI::Struct then write_bytes what.pointer.read_bytes(what.size)
			when String      then write_bytes what
			else raise ArgumentError, 'I do not know how to deal with this variable'
		end
	end
end

#write_array_of(type, data) ⇒ Object



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/ffi/extra.rb', line 143

def write_array_of (type, data)
	if type.is_a?(Symbol)
		if respond_to? "write_array_of_#{type}"
			return send "write_array_of_#{type}", data
		else
			type = FFI.find_type(type)
		end
	end

	type = type.native_type if type.respond_to? :native_type

	if type.is_a?(Class) && type.ancestors.member?(FFI::Struct)
		write_array_of_pointer(data)
	else
		begin
			send "write_array_of_#{type.name.downcase}", data
		rescue NameError
			raise ArgumentError, "#{type.name} is not supported"
		end
	end
end