pax_global_header00006660000000000000000000000064127373550060014522gustar00rootroot0000000000000052 comment=7262c8a97e5ab5c29246448c0a8651c46247f64b ffi-compiler-1.0.1/000077500000000000000000000000001273735500600140755ustar00rootroot00000000000000ffi-compiler-1.0.1/.gitignore000066400000000000000000000002771273735500600160730ustar00rootroot00000000000000doc/ .yardoc *.orig nbproject/private pkg *.orig *.rej *.patch *.diff build *.so *.dylib *.[oa] *.gem core lib/ffi/types.conf lib/ffi_c.bundle lib/ffi_c.so .idea *.iml /example/ext/example.h ffi-compiler-1.0.1/Gemfile000066400000000000000000000000461273735500600153700ustar00rootroot00000000000000source 'https://rubygems.org' gemspec ffi-compiler-1.0.1/LICENSE000066400000000000000000000261361273735500600151120ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ffi-compiler-1.0.1/README.md000066400000000000000000000033411273735500600153550ustar00rootroot00000000000000 [ffi-compiler](https://github.com/ffi/ffi-compiler) is a ruby library for automating compilation of native libraries for use with [ffi](https://github.com/ffi/ffi) To use, define your own ruby->native API using ffi, implement it in C, then use ffi-compiler to compile it. Example ------ ###### Directory layout lib |- example |- example.rb ext |- example.c |- Rakefile example.gemspec ###### lib/example/example.rb require 'ffi' require 'ffi-compiler/loader' module Example extend FFI::Library ffi_lib FFI::Compiler::Loader.find('example') # example function which takes no parameters and returns long attach_function :example, [], :long end ###### ext/example.c long example(void) { return 0xdeadbeef; } ###### ext/Rakefile require 'ffi-compiler/compile_task' FFI::Compiler::CompileTask.new('example') do |c| c.have_header?('stdio.h', '/usr/local/include') c.have_func?('puts') c.have_library?('z') end ###### example.gemspec Gem::Specification.new do |s| s.extensions << 'ext/Rakefile' s.name = 'example' s.version = '0.0.1' s.email = 'ffi-example' s.files = %w(example.gemspec) + Dir.glob("{lib,spec,ext}/**/*") s.add_dependency 'rake' s.add_dependency 'ffi-compiler' end ###### Build gem and install it gem build example.gemspec && gem install example-0.0.1.gem Successfully built RubyGem Name: example Version: 0.0.1 File: example-0.0.1.gem Building native extensions. This could take a while... Successfully installed example-0.0.1 ###### Test it $ irb 2.0.0dev :001 > require 'example/example' => true 2.0.0dev :002 > puts "Example.example=#{Example.example.to_s(16)}" Example.example=deadbeef => nil ffi-compiler-1.0.1/Rakefile000066400000000000000000000001411273735500600155360ustar00rootroot00000000000000require 'rubygems' require 'rubygems/tasks' Gem::Tasks.new do |t| t.scm.tag.format = '%s' end ffi-compiler-1.0.1/certs/000077500000000000000000000000001273735500600152155ustar00rootroot00000000000000ffi-compiler-1.0.1/certs/stakach.pem000066400000000000000000000025121273735500600173360ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIDvDCCAqSgAwIBAgIBATANBgkqhkiG9w0BAQUFADBaMQ4wDAYDVQQDDAVzdGV2 ZTEfMB0GCgmSJomT8ixkARkWD2FkdmFuY2VkY29udHJvbDETMBEGCgmSJomT8ixk ARkWA2NvbTESMBAGCgmSJomT8ixkARkWAmF1MB4XDTE2MDYyNjIyMjMyMloXDTE3 MDYyNjIyMjMyMlowWjEOMAwGA1UEAwwFc3RldmUxHzAdBgoJkiaJk/IsZAEZFg9h ZHZhbmNlZGNvbnRyb2wxEzARBgoJkiaJk/IsZAEZFgNjb20xEjAQBgoJkiaJk/Is ZAEZFgJhdTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKvI6Zfmxakj ADC7rWDhCtHDSCdn2jrzeMDO2xqq9P315j0x7YVglKF49Xz7OCnWGxn0Zzec22Ha xq2St09wLPtE6+/qTiq48ffxLKPR/Aahdk31HGx5AXDjRQ5p48m5CK3BDratshbi ssg2bVMOxMSnNowb5Mqc448X2shYHwfuo9C4fsvkn0eC+XtpwOKBsLJnmYxI8opB A6cL5onHD1JH5Ywt7mWn3XCGEZY98Hq3V7wpCACWSHP9FfCmf0Vyn30UTlBivoUh qmtLB+TDW4Qvma/1cc7p1e3HF9xQHSza9FTyfhzw/vxnSF+jT4upUtXdhCTMqqDv m597hs3/6z8CAwEAAaOBjDCBiTAJBgNVHRMEAjAAMAsGA1UdDwQEAwIEsDAdBgNV HQ4EFgQUqqCOTfINjbAqX/8nFvbzHcYG8xIwJwYDVR0RBCAwHoEcc3RldmVAYWR2 YW5jZWRjb250cm9sLmNvbS5hdTAnBgNVHRIEIDAegRxzdGV2ZUBhZHZhbmNlZGNv bnRyb2wuY29tLmF1MA0GCSqGSIb3DQEBBQUAA4IBAQB/DUhYFbdLHAuZMgjwNUxF tnf3a2o40p9mEtVm48yxfP9/9w6xh+gRN/rbBCkKbe2zSue9Nnr3zfKNONfqePlz 9BZOMx7LO/wFOkuWONIU+U7v5Obxi7a0bjZ6OQnY5M6FpuWG5RT6hVIlkbrh40Xd SgbJ2CyHXTL3tC7ykvvI5nXQLE6OG8lyHk5Cop2Lbm4qeBVCVEDgDsXi/PFP+hjk wpN2wi2CVPoj+c4bOYxgvF17WNGDWYdVEXXCRzoqGbA2kLbTH1o9BxI6NBzmfwyH LY7uYxN8Hy8S4Oto/gB1eREHqYwwXt3TmlJ6kAVGbO5y9xblPncdnfwNLCUnPfxN -----END CERTIFICATE----- ffi-compiler-1.0.1/example/000077500000000000000000000000001273735500600155305ustar00rootroot00000000000000ffi-compiler-1.0.1/example/Rakefile000066400000000000000000000006061273735500600171770ustar00rootroot00000000000000require 'rubygems' require 'rubygems/package_task' require 'ffi-compiler/export_task' def gem_spec @gem_spec ||= Gem::Specification.load('example.gemspec') end FFI::Compiler::ExportTask.new('lib/example', 'ext', :gem_spec => gem_spec) do |t| t.export 'example.rb' end Gem::PackageTask.new(gem_spec) do |pkg| pkg.need_zip = true pkg.need_tar = true pkg.package_dir = 'pkg' end ffi-compiler-1.0.1/example/example.gemspec000066400000000000000000000010611273735500600205260ustar00rootroot00000000000000Gem::Specification.new do |s| s.name = 'example' s.version = '0.0.1' s.author = 'E. Xample' s.email = 'ffi-example@example.com' s.homepage = 'http://wiki.github.com/ffi/ffi' s.summary = 'Ruby FFI example' s.description = 'Ruby FFI example' s.files = %w(Rakefile example.gemspec) + Dir.glob("{lib,spec,ext}/**/*") s.has_rdoc = false s.license = 'unknown' s.required_ruby_version = '>= 1.9.3' s.extensions << 'ext/Rakefile' s.add_dependency 'rake' s.add_dependency 'ffi-compiler', '>= 0.0.2' s.add_development_dependency 'rspec' end ffi-compiler-1.0.1/example/ext/000077500000000000000000000000001273735500600163305ustar00rootroot00000000000000ffi-compiler-1.0.1/example/ext/Rakefile000066400000000000000000000005301273735500600177730ustar00rootroot00000000000000require 'ffi-compiler/compile_task' FFI::Compiler::CompileTask.new('example') do |t| t.have_header?('stdio.h', '/usr/local/include') t.have_func?('puts') t.have_library?('z') t.cflags << "-arch x86_64 -arch i386" if t.platform.mac? t.ldflags << "-arch x86_64 -arch i386" if t.platform.mac? t.export '../lib/example/example.rb' end ffi-compiler-1.0.1/example/ext/example.c000066400000000000000000000003471273735500600201330ustar00rootroot00000000000000#include "example.h" RBFFI_EXPORT long example(void) { return 0xdeadbeef; } RBFFI_EXPORT int foo(struct Example_Foo *foo) { return 0; } RBFFI_EXPORT int bar(struct Example_Bar bar, struct Example_Foo *foo) { return 0; } ffi-compiler-1.0.1/example/lib/000077500000000000000000000000001273735500600162765ustar00rootroot00000000000000ffi-compiler-1.0.1/example/lib/example/000077500000000000000000000000001273735500600177315ustar00rootroot00000000000000ffi-compiler-1.0.1/example/lib/example/example.rb000066400000000000000000000006321273735500600217120ustar00rootroot00000000000000require 'ffi' require 'ffi-compiler/loader' module Example extend FFI::Library ffi_lib FFI::Compiler::Loader.find('example') class Foo < FFI::Struct layout :a, :int, :b, :int end class Bar < FFI::Struct layout :foo, Foo, :foo_ptr, Foo.by_ref end attach_function :example, [], :long attach_function :foo, [ Foo ], :int attach_function :bar, [ Bar.by_value, Foo ], :int end ffi-compiler-1.0.1/ffi-compiler.gemspec000066400000000000000000000014001273735500600200110ustar00rootroot00000000000000Gem::Specification.new do |s| s.name = 'ffi-compiler' s.version = '1.0.1' s.author = 'Wayne Meissner' s.email = ['wmeissner@gmail.com', 'steve@advancedcontrol.com.au'] s.cert_chain = ['certs/stakach.pem'] s.signing_key = File.expand_path("~/.ssh/gem-private_key.pem") if $0 =~ /gem\z/ s.homepage = 'http://wiki.github.com/ffi/ffi' s.summary = 'Ruby FFI Rakefile generator' s.description = 'Ruby FFI library' s.files = %w(ffi-compiler.gemspec Gemfile Rakefile README.md LICENSE) + Dir.glob("{lib,spec}/**/*") s.has_rdoc = false s.license = 'Apache 2.0' s.required_ruby_version = '>= 1.9' s.add_dependency 'rake' s.add_dependency 'ffi', '>= 1.0.0' s.add_development_dependency 'rspec' s.add_development_dependency 'rubygems-tasks' end ffi-compiler-1.0.1/lib/000077500000000000000000000000001273735500600146435ustar00rootroot00000000000000ffi-compiler-1.0.1/lib/ffi-compiler/000077500000000000000000000000001273735500600172175ustar00rootroot00000000000000ffi-compiler-1.0.1/lib/ffi-compiler/compile_task.rb000066400000000000000000000156141273735500600222250ustar00rootroot00000000000000require 'rake' require 'rake/tasklib' require 'rake/clean' require 'ffi' require 'tmpdir' require 'rbconfig' require_relative 'platform' module FFI module Compiler DEFAULT_CFLAGS = %w(-fexceptions -O -fno-omit-frame-pointer -fno-strict-aliasing) DEFAULT_LDFLAGS = %w(-fexceptions) class CompileTask < Rake::TaskLib attr_reader :cflags, :cxxflags, :ldflags, :libs, :platform attr_accessor :name, :ext_dir, :source_dirs, :exclude def initialize(name) @name = File.basename(name) @ext_dir = File.dirname(name) @source_dirs = [@ext_dir] @exclude = [] @defines = [] @include_paths = [] @library_paths = [] @libraries = [] @headers = [] @functions = [] @cflags = DEFAULT_CFLAGS.dup @cxxflags = DEFAULT_CFLAGS.dup @ldflags = DEFAULT_LDFLAGS.dup @libs = [] @platform = Platform.system @exports = [] yield self if block_given? define_task! end def add_include_path(path) @include_paths << path end def add_define(name, value=1) @defines << "-D#{name}=#{value}" end def have_func?(func) main = <<-C_FILE extern void #{func}(); int main(int argc, char **argv) { #{func}(); return 0; } C_FILE if try_compile(main) @functions << func return true end false end def have_header?(header, *paths) try_header(header, @include_paths) || try_header(header, paths) end def have_library?(libname, *paths) try_library(libname, paths: @library_paths) || try_library(libname, paths: paths) end def have_library(lib, func = nil, headers = nil, &b) try_library(lib, function: func, headers: headers, paths: @library_paths) end def find_library(lib, func, *paths) try_library(lib, function: func, paths: @library_paths) || try_library(libname, function: func, paths: paths) end def export(rb_file) @exports << { :rb_file => rb_file, :header => File.join(@ext_dir, File.basename(rb_file).sub(/\.rb$/, '.h')) } end private def define_task! pic_flags = %w(-fPIC) so_flags = [] if @platform.mac? pic_flags = [] so_flags << '-bundle' elsif @platform.name =~ /linux/ so_flags << "-shared -Wl,-soname,#{lib_name}" else so_flags << '-shared' end so_flags = so_flags.join(' ') out_dir = "#{@platform.arch}-#{@platform.os}" if @ext_dir != '.' out_dir = File.join(@ext_dir, out_dir) end directory(out_dir) CLOBBER.include(out_dir) lib_name = File.join(out_dir, Platform.system.map_library_name(@name)) iflags = @include_paths.uniq.map { |p| "-I#{p}" } @defines << @functions.uniq.map { |f| "-DHAVE_#{f.upcase}=1" } @defines << @headers.uniq.map { |h| "-DHAVE_#{h.upcase.sub(/\./, '_')}=1" } cflags = (@cflags + pic_flags + iflags + @defines).join(' ') cxxflags = (@cxxflags + @cflags + pic_flags + iflags + @defines).join(' ') ld_flags = (@library_paths.map { |path| "-L#{path}" } + @ldflags).join(' ') libs = (@libraries.map { |l| "-l#{l}" } + @libs).join(' ') src_files = [] obj_files = [] @source_dirs.each do |dir| files = FileList["#{dir}/**/*.{c,cpp}"] unless @exclude.empty? files.delete_if { |f| f =~ Regexp.union(*@exclude) } end src_files += files obj_files += files.ext('.o').map { |f| File.join(out_dir, f.sub(/^#{dir}\//, '')) } end index = 0 src_files.each do |src| obj_file = obj_files[index] if src =~ /\.c$/ file obj_file => [ src, File.dirname(obj_file) ] do |t| sh "#{cc} #{cflags} -o #{t.name} -c #{t.prerequisites[0]}" end else file obj_file => [ src, File.dirname(obj_file) ] do |t| sh "#{cxx} #{cxxflags} -o #{t.name} -c #{t.prerequisites[0]}" end end CLEAN.include(obj_file) index += 1 end ld = src_files.detect { |f| f =~ /\.cpp$/ } ? cxx : cc # create all the directories for the output files obj_files.map { |f| File.dirname(f) }.sort.uniq.map { |d| directory d } desc "Build dynamic library" file lib_name => obj_files do |t| sh "#{ld} #{so_flags} -o #{t.name} #{t.prerequisites.join(' ')} #{ld_flags} #{libs}" end CLEAN.include(lib_name) @exports.each do |e| desc "Export #{e[:rb_file]}" file e[:header] => [ e[:rb_file] ] do |t| ruby "-I#{File.join(File.dirname(__FILE__), 'fake_ffi')} -I#{File.dirname(t.prerequisites[0])} #{File.join(File.dirname(__FILE__), 'exporter.rb')} #{t.prerequisites[0]} #{t.name}" end obj_files.each { |o| file o => [ e[:header] ] } CLEAN.include(e[:header]) desc "Export API headers" task :api_headers => [ e[:header] ] end task :default => [ lib_name ] task :package => [ :api_headers ] end def try_header(header, paths) main = <<-C_FILE #include <#{header}> int main(int argc, char **argv) { return 0; } C_FILE if paths.empty? && try_compile(main) @headers << header return true end paths.each do |path| if try_compile(main, "-I#{path}") @include_paths << path @headers << header return true end end false end def try_library(libname, options = {}) func = options[:function] || 'main' paths = options[:paths] || '' main = <<-C_FILE #{(options[:headers] || []).map {|h| "#include <#{h}>"}.join('\n')} extern int #{func}(); int main() { return #{func}(); } C_FILE if paths.empty? && try_compile(main) @libraries << libname return true end paths.each do |path| if try_compile(main, "-L#{path}", "-l#{libname}") @library_paths << path @libraries << libname end end end def try_compile(src, *opts) Dir.mktmpdir do |dir| path = File.join(dir, 'ffi-test.c') File.open(path, 'w') do |f| f << src end cflags = opts.join(' ') output = File.join(dir, 'ffi-test') begin return system "#{cc} #{cflags} -o #{output} -c #{path} > #{path}.log 2>&1" rescue return false end end end def cc @cc ||= (ENV['CC'] || RbConfig::CONFIG['CC'] || 'cc') end def cxx @cxx ||= (ENV['CXX'] || RbConfig::CONFIG['CXX'] || 'c++') end end end end ffi-compiler-1.0.1/lib/ffi-compiler/export_task.rb000066400000000000000000000025111273735500600221060ustar00rootroot00000000000000require 'rake' require 'rake/tasklib' require 'rake/clean' module FFI module Compiler class ExportTask < Rake::TaskLib def initialize(rb_dir, out_dir, options = {}) @rb_dir = rb_dir @out_dir = out_dir @gem_spec = options[:gem_spec] @exports = [] if block_given? yield self define_tasks! end end def export(rb_file) @exports << { :rb_file => File.join(@rb_dir, rb_file), :header => File.join(@out_dir, File.basename(rb_file).sub(/\.rb$/, '.h')) } end def export_all Dir["#@rb_dir/**/*rb"].each do |rb_file| @exports << { :rb_file => rb_file, :header => File.join(@out_dir, File.basename(rb_file).sub(/\.rb$/, '.h')) } end end private def define_tasks! @exports.each do |e| file e[:header] => [ e[:rb_file] ] do |t| ruby "-I#{File.join(File.dirname(__FILE__), 'fake_ffi')} #{File.join(File.dirname(__FILE__), 'exporter.rb')} #{t.prerequisites[0]} #{t.name}" end CLEAN.include(e[:header]) desc "Export API headers" task :api_headers => [ e[:header] ] @gem_spec.files << e[:header] unless @gem_spec.nil? end task :gem => [ :api_headers ] unless @gem_spec.nil? end end end end ffi-compiler-1.0.1/lib/ffi-compiler/exporter.rb000066400000000000000000000000671273735500600214170ustar00rootroot00000000000000require 'ffi' load ARGV[0] FFI.exporter.dump(ARGV[1]) ffi-compiler-1.0.1/lib/ffi-compiler/fake_ffi/000077500000000000000000000000001273735500600207515ustar00rootroot00000000000000ffi-compiler-1.0.1/lib/ffi-compiler/fake_ffi/ffi-compiler/000077500000000000000000000000001273735500600233255ustar00rootroot00000000000000ffi-compiler-1.0.1/lib/ffi-compiler/fake_ffi/ffi-compiler/loader.rb000066400000000000000000000001451273735500600251200ustar00rootroot00000000000000module FFI module Compiler module Loader def self.find(*args) end end end endffi-compiler-1.0.1/lib/ffi-compiler/fake_ffi/ffi.rb000066400000000000000000000145671273735500600220570ustar00rootroot00000000000000module 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 endffi-compiler-1.0.1/lib/ffi-compiler/loader.rb000066400000000000000000000017761273735500600210250ustar00rootroot00000000000000require 'pathname' require 'ffi' require_relative 'platform' module FFI module Compiler module Loader def self.find(name, start_path = nil) library = Platform.system.map_library_name(name) root = false Pathname.new(start_path || caller_path(caller[0])).ascend do |path| Dir.glob("#{path}/**/{#{FFI::Platform::ARCH}-#{FFI::Platform::OS}/#{library},#{library}}") do |f| return f end break if root # Next iteration will be the root of the gem if this is the lib/ dir - stop after that root = File.basename(path) == 'lib' end raise LoadError.new("cannot find '#{name}' library") end def self.caller_path(line = caller[0]) if FFI::Platform::OS == 'windows' drive = line[0..1] path = line[2..-1].split(/:/)[0] full_path = drive + path else full_path = line.split(/:/)[0] end File.dirname full_path end end end endffi-compiler-1.0.1/lib/ffi-compiler/platform.rb000066400000000000000000000007471273735500600214000ustar00rootroot00000000000000module FFI::Compiler class Platform LIBSUFFIX = FFI::Platform.mac? ? 'bundle' : FFI::Platform::LIBSUFFIX def self.system @@system ||= Platform.new end def map_library_name(name) "#{FFI::Platform::LIBPREFIX}#{name}.#{LIBSUFFIX}" end def arch FFI::Platform::ARCH end def os FFI::Platform::OS end def name FFI::Platform.name end def mac? FFI::Platform.mac? end end endffi-compiler-1.0.1/lib/ffi-compiler/task.rb000066400000000000000000000003751273735500600205130ustar00rootroot00000000000000require 'rake' require 'rake/tasklib' require 'rake/clean' require 'ffi' require 'tmpdir' require 'rbconfig' require_relative 'compile_task' module FFI module Compiler class Task < CompileTask warn "#{self} is deprecated" end end end