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

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

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



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

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
    system("#{make} clean") if File.exist?('Makefile')
    write_files(n[:mod])

    pid = fork do
      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
  end

  return n[:ld]
end

#names(file) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/cplus2ruby/compiler.rb', line 70

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

#startup(file, force_compilation = false, cflags = "", libs = "", &block) ⇒ Object



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

def startup(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

#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