Class: Cplus2Ruby::Compiler

Inherits:
Object
  • Object
show all
Defined in:
lib/cplus2ruby/compiler.rb

Instance Method Summary collapse

Constructor Details

#initialize(model = Cplus2Ruby.model) ⇒ Compiler

Returns a new instance of Compiler.



5
6
7
# File 'lib/cplus2ruby/compiler.rb', line 5

def initialize(model=Cplus2Ruby.model)
  @model = model
end

Instance Method Details

#commit(file, force_compilation = false, cflags = "", libs = "", &block) ⇒ Object Also known as: startup



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/cplus2ruby/compiler.rb', line 16

def commit(file, force_compilation=false, cflags="", libs="", &block) 
  n = names(file)

  if not force_compilation
    begin
      require n[:ld]
      block.call if block
      return
    rescue LoadError
    end
  end

  compile(file, cflags, libs)
  require n[:ld]
  block.call if block
end

#compile(file, cflags = "", libs = "") ⇒ Object

Compiles file. Returns the name of the shared object to use by require.



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
# File 'lib/cplus2ruby/compiler.rb', line 39

def compile(file, cflags="", libs="")
  n = names(file)

  require 'win32/process' if RUBY_PLATFORM.match('mswin')
  require 'fileutils'

  FileUtils.mkdir_p(n[:dir])

  make = RUBY_PLATFORM.match('mswin') ? 'nmake' : 'make'

  Dir.chdir(n[:dir]) do
    if File.exist?('Makefile')
      system("#{make} clean") 
      File.delete('Makefile')
    end
    write_files(n[:mod])
  end

  pid = fork do
    Dir.chdir(n[:dir])
    $configure_args = {"--srcdir" => Dir.pwd}
    require 'mkmf'
    $CFLAGS = cflags
    $LIBS << (" -lstdc++ " + libs)
    create_makefile(n[:mod])
    exec "#{make}"
  end
  _, status = Process.waitpid2(pid)

  if RUBY_PLATFORM.match('mswin')
    raise if status != 0
  else
    raise if status.exitstatus != 0
  end

  return n[:ld]
end

#names(file) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/cplus2ruby/compiler.rb', line 77

def names(file) 
  require 'rbconfig'
  base = File.basename(file)
  dir = File.dirname(file)
  mod, ext = base.split(".") 
  ld = "#{dir}/#{mod}.#{Config::CONFIG['DLEXT']}"
  { :file => file,
    :base => base,
    :dir  => dir,
    :mod  => mod,
    :ext  => ext,
    :ld   => ld }
end

#write_files(mod_name) ⇒ Object



9
10
11
12
13
14
# File 'lib/cplus2ruby/compiler.rb', line 9

def write_files(mod_name)
  cpp_cg = Cplus2Ruby::CppCodeGenerator.new(@model)
  wrap_cg = Cplus2Ruby::WrapperCodeGenerator.new(@model)
  cpp_cg.write_files(mod_name)
  wrap_cg.write_files(mod_name)
end