File: ffi.rb

package info (click to toggle)
ruby-ffi-compiler 1.0.1-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 156 kB
  • sloc: ruby: 556; ansic: 16; makefile: 4
file content (282 lines) | stat: -rw-r--r-- 6,519 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
module FFI

  def self.exporter=(exporter)
    @@exporter = exporter
  end

  def self.exporter
    @@exporter ||= Exporter.new(nil)
  end

  class Type
    attr_reader :name
    def initialize(name)
      @name = name
    end
  end
  
  class StructByReference < Type
    def initialize(struct_class)
      super("struct #{struct_class.to_s.gsub('::', '_')} *")
    end
  end

  class StructByValue < Type
    def initialize(struct_class)
      super("struct #{struct_class.to_s.gsub('::', '_')}")
    end
  end

  class CallbackInfo
    attr_reader :return_type
    attr_reader :arg_types
    attr_reader :options

    def initialize(return_type, arg_types = [], *other)
      @return_type = return_type
      @arg_types = arg_types
      @options = options
    end

    def name(name)
      params = @arg_types.empty? ? 'void' : @arg_types.map(&:name).join(', ')
      "#{@return_type.name} (*#{name})(#{params})"
    end
  end

  PrimitiveTypes = {
      :void => 'void',
      :bool => 'bool',
      :string => 'const char *',
      :char => 'char',
      :uchar => 'unsigned char',
      :short => 'short',
      :ushort => 'unsigned short',
      :int => 'int',
      :uint => 'unsigned int',
      :long => 'long',
      :ulong => 'unsigned long',
      :long_long => 'long long',
      :ulong_long => 'unsigned long long',
      :float => 'float',
      :double => 'double',
      :long_double => 'long double',
      :pointer => 'void *',
      :int8 => 'int8_t',
      :uint8 => 'uint8_t',
      :int16 => 'int16_t',
      :uint16 => 'uint16_t',
      :int32 => 'int32_t',
      :uint32 => 'uint32_t',
      :int64 => 'int64_t',
      :uint64 => 'uint64_t',
      :buffer_in => 'const in void *',
      :buffer_out => 'out void *',
      :buffer_inout => 'inout void *',
      :varargs => '...'
  }

  TypeMap = {}
  def self.find_type(type)
    return type if type.is_a?(Type) or type.is_a?(CallbackInfo)

    t = TypeMap[type]
    return t unless t.nil?

    if PrimitiveTypes.has_key?(type)
      return TypeMap[type] = Type.new(PrimitiveTypes[type])
    end
    raise TypeError.new("cannot resolve type #{type}")
  end

  class Function
    def initialize(*args)
    end
  end

  class Exporter
    attr_accessor :mod
    attr_reader :functions, :callbacks, :structs

    def initialize(mod)
      @mod = mod
      @functions = []
      @callbacks = {}
      @structs = []
    end

    def attach(mname, fname, result_type, param_types)
      @functions << { mname: mname, fname: fname, result_type: result_type, params: param_types.dup }
    end
    
    def struct(name, fields)
      @structs << { name: name, fields: fields.dup }
    end

    def callback(name, cb)
      @callbacks[name] = cb
    end

    def dump(out_file)
      File.open(out_file, 'w') do |f|
        guard = File.basename(out_file).upcase.gsub('.', '_').gsub('/', '_')
        f.puts <<-HEADER
#ifndef #{guard}
#define #{guard} 1

#ifndef RBFFI_EXPORT
# ifdef __cplusplus
#  define RBFFI_EXPORT extern "C"
# else
#  define RBFFI_EXPORT
# endif
#endif

        HEADER

        @callbacks.each do |name, cb|
          f.puts "typedef #{cb.name(name)};"
        end
        @structs.each do |s|
          f.puts "struct #{s[:name].gsub('::', '_')} {"
          s[:fields].each do |field|
            if field[:type].is_a?(CallbackInfo)
              type = field[:type].name(field[:name].to_s)
            else
              type = "#{field[:type].name} #{field[:name].to_s}"
            end
            f.puts "#{' ' * 4}#{type};"
          end
          f.puts '};'
          f.puts
        end
        @functions.each do |fn|
          param_string = fn[:params].empty? ? 'void' : fn[:params].map(&:name).join(', ')
          f.puts "RBFFI_EXPORT #{fn[:result_type].name} #{fn[:fname]}(#{param_string});"
        end
        f.puts <<-EPILOG

#endif /* #{guard} */
        EPILOG
      end
    end
    
  end

  module Library
    def self.extended(mod)
      FFI.exporter.mod = mod
    end

    def attach_function(name, func, args, returns = nil, options = nil)
      mname, a2, a3, a4, a5 = name, func, args, returns, options
      cname, arg_types, ret_type, opts = (a4 && (a2.is_a?(String) || a2.is_a?(Symbol))) ? [ a2, a3, a4, a5 ] : [ mname.to_s, a2, a3, a4 ]
      arg_types = arg_types.map { |e| find_type(e) }
      FFI.exporter.attach(mname, cname, find_type(ret_type), arg_types)
    end

    def ffi_lib(*args)

    end

    def callback(*args)
      name, params, ret = if args.length == 3
        args
      else
        [ nil, args[0], args[1] ]
      end
      native_params = params.map { |e| find_type(e) }
      cb = FFI::CallbackInfo.new(find_type(ret), native_params)
      FFI.exporter.callback(name, cb) if name
    end

    TypeMap = {}
    def find_type(type)
      t = TypeMap[type]
      return t unless t.nil?
      
      if type.is_a?(Class) && type < Struct
        return TypeMap[type] = StructByReference.new(type)
      end

      TypeMap[type] = FFI.find_type(type)
    end
  end

  class Struct
    def self.layout(*args)
      return if args.size.zero?
      fields = []
      if args.first.kind_of?(Hash)
        args.first.each do |name, type|
          fields << { :name => name, :type => find_type(type), :offset => nil }
        end
      else
        i = 0
        while i < args.size
          name, type, offset = args[i], args[i+1], nil
          i += 2
          if args[i].kind_of?(Integer)
            offset = args[i]
            i += 1
          end
          fields << { :name => name, :type => find_type(type), :offset => offset }
        end
      end
      FFI.exporter.struct(self.to_s, fields)
    end

    def initialize
      @data = {}
    end

    def [](name)
      @data[name]
    end

    def []=(name, value)
      @data[name] = value
    end

    def self.callback(params, ret)
      FFI::CallbackInfo.new(find_type(ret), params.map { |e| find_type(e) })
    end

    TypeMap = {}
    def self.find_type(type)
      t = TypeMap[type]
      return t unless t.nil?

      if type.is_a?(Class) && type < Struct
        return TypeMap[type] = StructByValue.new(type)
      end

      TypeMap[type] = FFI.find_type(type)
    end

    def self.in
      ptr(:in)
    end

    def self.out
      ptr(:out)
    end

    def self.ptr(flags = :inout)
      StructByReference.new(self)
    end

    def self.val
      StructByValue.new(self)
    end

    def self.by_value
      self.val
    end

    def self.by_ref(flags = :inout)
      self.ptr(flags)
    end

  end
end