Git Product home page Git Product logo

ffi's Introduction

Description

Ruby-FFI is a gem for programmatically loading dynamically-linked native libraries, binding functions within them, and calling those functions from Ruby code. Moreover, a Ruby-FFI extension works without changes on CRuby (MRI), JRuby, Rubinius and TruffleRuby. Discover why you should write your next extension using Ruby-FFI.

Features

  • Intuitive DSL
  • Supports all C native types
  • C structs (also nested), enums and global variables
  • Callbacks from C to Ruby
  • Automatic garbage collection of native memory
  • Usable in Ractor: How-to-use-FFI-in-Ruby-Ractors

Synopsis

require 'ffi'

module MyLib
  extend FFI::Library
  ffi_lib 'c'
  attach_function :puts, [ :string ], :int
end

MyLib.puts 'Hello, World using libc!'

For less minimalistic and more examples you may look at:

Requirements

When installing the gem on CRuby (MRI), you will need:

  • A C compiler (e.g., Xcode on macOS, gcc or clang on everything else) Optionally (speeds up installation):
  • The libffi library and development headers - this is commonly in the libffi-dev or libffi-devel packages

The ffi gem comes with a builtin libffi version, which is used, when the system libffi library is not available or too old. Use of the system libffi can be enforced by:

gem install ffi -- --enable-system-libffi        # to install the gem manually
bundle config build.ffi --enable-system-libffi   # for bundle install

or prevented by --disable-system-libffi.

On Linux systems running with PaX (Gentoo, Alpine, etc.), FFI may trigger mprotect errors. You may need to disable mprotect for ruby (paxctl -m [/path/to/ruby]) for the time being until a solution is found.

On FreeBSD systems pkgconf must be installed for the gem to be able to compile using clang. Install either via packages pkg install pkgconf or from ports via devel/pkgconf.

On JRuby and TruffleRuby, there are no requirements to install the FFI gem, and require 'ffi' works even without installing the gem (i.e., the gem is preinstalled on these implementations).

Installation

From rubygems:

[sudo] gem install ffi

From a Gemfile using git or GitHub

gem 'ffi', github: 'ffi/ffi', submodules: true

or from the git repository on github:

git clone git://github.com/ffi/ffi.git
cd ffi
git submodule update --init --recursive
bundle install
rake install

Install options:

  • --enable-system-libffi : Force usage of system libffi
  • --disable-system-libffi : Force usage of builtin libffi
  • --enable-libffi-alloc : Force closure allocation by libffi
  • --disable-libffi-alloc : Force closure allocation by builtin method

License

The ffi library is covered by the BSD license, also see the LICENSE file. The specs are covered by the same license as ruby/spec, the MIT license.

Credits

The following people have submitted code, bug reports, or otherwise contributed to the success of this project:

ffi's People

Contributors

ahorek avatar andrewdotn avatar burgestrand avatar byroot avatar cfis avatar chrisseaton avatar enebo avatar eregon avatar flavorjones avatar graywolf avatar headius avatar hobophobe avatar ivoanjo avatar kerilk avatar larskanis avatar lucsky avatar matoro avatar mvz avatar nirvdrum avatar olleolleolle avatar paradoxv5 avatar pck avatar postmodern avatar sdaubert avatar tduehr avatar terceiro avatar tmm1 avatar vp-of-awesome avatar watson1978 avatar wycats avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ffi's Issues

FFI::Struct.new always zeroes memory allocation

When calling Struct.new, it calls struct_malloc (Struct.c line 176) which creates a MemoryPointer and passes in the parameter to zero/initialize the memory. There are many situations where this is completely unnecessary work.

e.g.
struct foo {
int bar;
long baz;
void *qux;
};

struct foo foo_var;

api_call_initializes_struct(&foo_var);

The API is just going to overlay the memory with its own data or zero it out itself.

So, please provide a way to pass through an argument to Struct.new that disables memory initialization.

Unusual exception when accessing enum fields of a Struct.

I've been working on a FFI library for libudis86, which uses a certain enum (ud_vendor) in a Struct definition. In my version I did the same, although when accessing the enum field in the specs I receive this exception:

ArgumentError in 'FFI::UDis86::UD create should accept a :vendor option'
get not supported for FFI::StructLayout::Field
./spec/ud_spec.rb:23:
/usr/lib64/ruby/1.8/timeout.rb:53:in `timeout'

The offending spec:

it "should accept a :vendor option" do
  ud = UD.create(:vendor => :amd)
  ud.vendor.should == :amd
end

And the Struct layout:

:pc, :uint64,
:vendor, :ud_vendor,
:mapen, :pointer,

I am using FFI 0.6.0 from github.

FFI 0.6.3 garbles Structs passed to functions by-value.

While developing FFI bindings to libmsgpack (github.com/postmodern/ffi-msgpack), I noticed that the msgpack_pack_object function would always return -1 for the Structs I passed to it. It appeared msgpack_pack_object was unable to recognize the type field of the msgpack_object struct and returned -1.

int msgpack_pack_object(msgpack_packer* pk, msgpack_object d)
{
switch(d.type) {
    // ....
        default:
    return -1;
}
}

I later verified this by passing the same msgpack_object structs to msgpack_object_print:

require 'ffi/msgpack'

obj = FFI::MsgPack::MsgObject.new_object(1)
# => #<FFI::MsgPack::MsgObject:0x000000020bbe00>
obj[:type]
# => :positive_integer
obj.pointer.get_bytes(0,8)
# => "\x03\x00\x00\x00\x00\x00\x00\x00"
obj[:values][:u64]
# => 1
stdout = FFI::LibC.fdopen(0,'w')
# => #<FFI::Pointer address=0x2252d20>
FFI::LibC.fflush stdout
# => 0
FFI::MsgPack.msgpack_object_print(stdout,obj)
# => nil
FFI::LibC.fflush stdout
#<UNKNOWN 32488 138993971994384>
# => 0

When msgpack_object_print cannot recognize the type field of the msgpack_object struct it will print this information:

void msgpack_object_print(FILE* out, msgpack_object o)
{
    switch(o.type) {
    // ...
    default:
    // FIXME
    fprintf(out, "#<UNKNOWN %hu %"PRIu64">", o.type, o.via.u64);
}

:varargs doesn't resolve enums properly and refuses standard types

Hi there,

I've found that the :varargs type doesn't work correctly if you have defined enums before you attach the function. Here's a sample code using GTK functions:

#!/usr/bin/env ruby
#Encoding: UTF-8
require "ffi"
module GTK
  extend FFI::Library

  ffi_lib "gtk-x11-2.0.so"

  enum :type, [ :gtk_message_info, 
                        :gtk_message_warning, 
                        :gtk_message_question, 
                        :gtk_message_error, 
                        :gtk_message_other
                      ]

  enum :buttons, [:gtk_buttons_none, 
                            :gtk_buttons_ok, 
                            :gtk_buttons_close, 
                            :gtk_buttons_cancel, 
                            :gtk_buttons_yes_no, 
                            :gtk_buttons_ok_cancel
                            ]

  attach_function(:gtk_init, [:pointer, :pointer], :void)
  attach_function(:gtk_set_locale, [], :void)
  attach_function(:gtk_message_dialog_new, [:pointer, :int, :type, :buttons, :string], :pointer)
  attach_function(:g_object_set, [:pointer, :varargs], :void) #Here's :varargs used
  attach_function(:gtk_dialog_run, [:pointer], :int)
  attach_function(:gtk_widget_destroy, [:pointer], :void)
end

GTK.gtk_init(nil, nil)
GTK.gtk_set_locale()
dialog = GTK.gtk_message_dialog_new(nil, 0, :gtk_message_info, :gtk_buttons_ok, "Title")
GTK.g_object_set(dialog, :string, "secondary-text", :string, "text", :pointer, nil)
GTK.gtk_dialog_run(dialog)
GTK.gtk_widget_destroy(dialog)

If I put the attaching of g_object_set before the enum definitions, this code works. Otherwise, this error results:

/opt/rubies/ruby-1.9.1-p378/lib/ruby/gems/1.9.1/gems/ffi-0.6.3/lib/ffi/types.rb:46:in `find_type': Unable to resolve type 'string' (TypeError)
  from /opt/rubies/ruby-1.9.1-p378/lib/ruby/gems/1.9.1/gems/ffi-0.6.3/lib/ffi/variadic.rb:47:in `call'
  from (eval):3:in `g_object_set'
  from gtk.rb:36:in `<main>'

Marvin

can't inherit and override new() for FFI::Buffer, Pointer, or MemoryPointer in JRuby

The code below works fine in MRI but not JRuby. The problem appears to be something strange going on when attempting to inherit from base types like FFI::Pointer, MemoryPointer, Buffer, etc. and overriding initialize() with a call to super().

http://gist.github.com/275646

Am I doing something wrong here? Guessing this has something to do with multiiple creators in the java implementation but that's just a shot in the dark. I dont really understand how JRuby's FFI is implemented well enough to investigate.

InlineArray breaks IRB

Something with overridden pretty_print or 'inspect' appears to be broken. When using any InlineArray struct field, IRB raises an exception as it fails to prettyprint the Array with an error like the following:

NoMethodError: to_s not defined for this array type

Please refer to http://gist.github.com/279607 for a full example, including backtrace.

ArgumentError "Cannot set :string fields"

Hello,

I ran into a "Cannot set :string fields" error from memory_op_put_strptr() in ext/ffi_c/AbstractMemory.c:389.

Is this functionality just not implemented yet (should have raised a NotImplementedError), or is there a reason why users are prohibited from assigning the result of FFI::MemoryPointer.from_string() to a :string field inside a FFI::Struct?

Thanks for your consideration.

using String or Symbol with ffi_lib

On MRI 1.9.1p243 (mingw32) and JRuby 1.4.0 running on a Windows system with the 0.5.1 FFI gem, you can specify the library to use with a Symbol like ffi_lib :kernel32

Attempting the same in a Ruby 1.8 environment gives a can't convert Symbol into String(TypeError) in map_library_name of ffi/ffi.rb due to File.basename in 1.8 not accepting Symbols.

While providing a String library name to ffi_lib works on both 1.8 and 1.9, it is inconsistent with FFI::Library#attach_function which accepts a Symbol as the C function name.

install issue ruby 1.8.7

Hi, trying to install under Ruby 1 8 7, debian
Thanks!

brianwolf@lightning:~$ gem install ffi WARNING: Installing to ~/.gem since /usr/lib/ruby/gems/1.8 and
/usr/bin aren't both writable.
Building native extensions. This could take a while...
ERROR: Error installing ffi:
ERROR: Failed to build gem native extension.

/usr/bin/ruby1.8 -rubygems /usr/lib/ruby/gems/1.8/gems/rake-0.8.7/bin/rake RUBYARCHDIR=/home/brianwolf/.gem/ruby/1.8/gems/ffi-0.6.2/lib RUBYLIBDIR=/home/brianwolf/.gem/ruby/1.8/gems/ffi-0.6.2/lib
/usr/bin/ruby1.8: no such file to load -- ubygems (LoadError)

Gem files will remain installed in /home/brianwolf/.gem/ruby/1.8/gems/ffi-0.6.2 for inspection.
Results logged to /home/brianwolf/.gem/ruby/1.8/gems/ffi-0.6.2/gen/gem_make.out
brianwolf@lightning:~$ ruby --version
ruby 1.8.7 (2008-08-11 patchlevel 72) [x86_64-linux]

Standardizing the FFI specs

http://github.com/ffi/ffi/tree/master/spec/ffi/

On Dec 4, 2009, at 2:51 PM, Brian Ford wrote:
The specs need quite a bit of cleanup to conform to the rubyspec style guide.

http://rubyspec.org/wiki/rubyspec/Style_Guide

mike dalessio wrote:
We've had a couple of threads about this in the last 6 months, and although
I think FFI developers are in favor of a unifying / standard test suite,
nobody has had the time or the will to be point-man for the project.

I'm willing to help unify and standardize, if someone is willing to
coordinate and pester all the people who need to be pestered.

Ernie wrote:
Deal.

http://groups.google.com/group/ruby-ffi/browse_thread/thread/e9a24d52f776ab04

rake fails if run from the root

rdp@li49-39:~/dev/downloads/ffi$ rake
(in /home/rdp/dev/downloads/ffi)
rake-compiler must be configured first to enable cross-compilation
rake-compiler must be configured first to enable cross-compilation
rake-compiler must be configured first to enable cross-compilation
rake-compiler must be configured first to enable cross-compilation
cd build/i686-linux/ffi_c/1.8.6
GNU Make 3.81
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.

This program built for i486-pc-linux-gnu
make
Configuring libffi
/bin/sh: Can't open ../../../../ext/ffi_c/libffi/configure
make: *** [/home/rdp/dev/downloads/ffi/build/i686-linux/ffi_c/1.8.6/libffi/.libs/libffi_convenience.a] Error 2
rake aborted!
Command failed with status (2): [make...]

(See full trace by running task with --trace)

however running ruby extconf.rb && make within the ext/ffi_c directory works, so I think it's just a path problem.
-r

FFI cannot map Integers to Symbols with large enums.

I've added a large enum (560 elements) named :ud_mnemonic_code to ffi-udis86. I've confirmed that I can manually map Integers to Symbols with the enum. But when I use the enum type in function or struct definitions, all Integers are mapped to nil.

ud = FFI::UDis86::UD.create { |ud| 0x90 }
ud.next_insn
# => 1
ud.to_asm
# => "nop "
ud[:mnemonic]
# => nil
ud.offset_of(:mnemonic)
# => 200
ud.to_ptr.get_uint(200)
# => 322
FFI::UDis86.enum_type(:ud_mnemonic_code)[322]
# => :ud_inop

http://github.com/sophsec/ffi-udis86/blob/master/lib/udis86/types.rb#L19
http://github.com/sophsec/ffi-udis86/blob/master/lib/udis86/ud.rb#L30

Automagic to infere library name fails with nested modules

Using multiple modules to avoid namespace pollution, the automagic detection of the library name fails:

module Windows
  module Kernel32
    extend FFI::Library
    # ffi_lib 'kernel32' # need to comment out to make it work

    attach_function :AllocConsole, [], :int32
    attach_function :GetLastError, [], :uint32
  end
end

Producing the following output while the ffi_lib invoke is still commented:

C:/Users/Luis/.gem/ruby/1.8/gems/ffi-0.5.1-x86-mingw32/lib/ffi/library.rb:77:in `attach_function': Function 'AllocConsole' not found in [[current process]] (FFI::NotFoundError)

I think this is because is using @self.name@ and not excluding the nested modules of it.

ffi_lib ignores .bundle libs

http://gist.github.com/367604

running

$ ruby extconf.rb
$ make
$ ruby issue.rb

results in
/Users/daniel/.rvm/gems/ruby-1.9.1-p378/gems/ffi-0.6.3/lib/ffi/library.rb:61:in block in ffi_lib': Could not open library 'issue': dlopen(issue, 5): image not found. Could not open library 'libissue.dylib': dlopen(libissue.dylib, 5): image not found (LoadError) but it should probably just load theissue.bundle`.
ffi_lib ["issue.bundle", "issue"]
can be used as a workaround.

Produced on OSX 10.6 Ruby 1.9.1

Function not found [NotFoundError]

I just tried to load s dylib on OSx 10.6 with ffi-0.6.3. Loading works fine but i get this error while attaching the function in my lib:

`attach_function': Function 'calc_a_lot' not found in libcalcalot.dylib

g++ compile line:
g++ -dynamiclib -o libcalcalot.dylib calc_a_lot.cpp

nm says the function is there:
.....
0000000000001016 (__TEXT,__text) external _Z9calcalotPKcS0
.....

FFI uint functions cannot return Integers on Ruby 1.9.1

I just upgraded to FFI 0.6.0 and noticed FFI functions that return uint types, attempt to return a String on Ruby 1.9.1. Example from the ffi-udis86 library (http://github.com/sophsec/ffi-udis86).

attach_function :ud_disassemble, [:pointer], :uint

require 'udis86'
FFI::UDis86::UD.open('file') do |ud|
  puts ud.next_insn.inspect
end
TypeError: can't convert String into Integer
from /underground/code/sophsec/ffi-udis86/lib/udis86/ud.rb:376:in `ud_disassemble'
from /underground/code/sophsec/ffi-udis86/lib/udis86/ud.rb:376:in `next_insn'
from (irb):3:in `block in irb_binding'
from /underground/code/sophsec/ffi-udis86/lib/udis86/ud.rb:152:in `call'
from /underground/code/sophsec/ffi-udis86/lib/udis86/ud.rb:152:in `block in open'
from /underground/code/sophsec/ffi-udis86/lib/udis86/ud.rb:149:in `open'
from /underground/code/sophsec/ffi-udis86/lib/udis86/ud.rb:149:in `open'
from (irb):3
from /usr/bin/irb19:12:in `<main>'

Unknown CPU when compiling on ARM architecture

I'm getting unknown CPU when trying to install the gem on a Sheeva Plug.

/proc/cpuinfo:

root@ubuntu:/var/lib/gems/1.8/gems/ffi-0.6.3/ext/ffi_c# cat /proc/cpuinfo
Processor : Feroceon 88FR131 rev 1 (v5l)
BogoMIPS : 1192.75
Features : swp half thumb fastmult edsp
CPU implementer : 0x56
CPU architecture: 5TE
CPU variant : 0x2
CPU part : 0x131
CPU revision : 1

Hardware : Marvell SheevaPlug Reference Board
Revision : 0000
Serial : 0000000000000000

Rakefile fails with recent Bones (3.2.0)

(in /var/tmp/portage/dev-ruby/ffi-0.5.4/work/all/ffi-ffi-57b5d81)
rake aborted!
undefined method `setup' for Bones:Module
/var/tmp/portage/dev-ruby/ffi-0.5.4/work/all/ffi-ffi-57b5d81/Rakefile:17
(See full trace by running task with --trace)

Error installing ffi on OS X Snow Leopard

$ sudo gem install ffi
Building native extensions. This could take a while...
ERROR: Error installing ffi:
ERROR: Failed to build gem native extension.

/opt/local/bin/ruby extconf.rb
checking for ffi.h in /usr/local/include,/opt/local/include... no
checking for ffi_call() in -lffi... yes
checking for ffi_prep_closure()... yes
checking for ffi_raw_call()... no
checking for rb_thread_blocking_region()... no
creating extconf.h
creating Makefile

make
/usr/bin/gcc-4.2 -I. -I. -I/opt/local/lib/ruby/1.8/i686-darwin10 -I. -DRUBY_EXTCONF_H="extconf.h" -I/opt/local/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -I/opt/local/include -fno-common -O2 -arch x86_64 -fno-common -pipe -fno-common -Werror -Wunused -Wformat -Wimplicit -Wreturn-type -arch x86_64 -c AbstractMemory.c
In file included from AbstractMemory.h:37,
from AbstractMemory.c:36:
Types.h:74:17: error: ffi.h: No such file or directory
In file included from Types.h:75,
from AbstractMemory.h:37,
from AbstractMemory.c:36:
Type.h:44: error: expected specifier-qualifier-list before ‘ffi_type’
In file included from AbstractMemory.c:38:
Function.h:52: error: expected specifier-qualifier-list before ‘ffi_type’
make: *** [AbstractMemory.o] Error 1

Gem files will remain installed in /opt/local/lib/ruby/gems/1.8/gems/ffi-0.5.4 for inspection.
Results logged to /opt/local/lib/ruby/gems/1.8/gems/ffi-0.5.4/ext/ffi_c/gem_make.out

First Windows example seg faults

The first Windows example seg faults (using ffi 0.6.2). In what way should the example be written such that it would work?
http://wiki.github.com/ffi/ffi/windows-examples

C:\Source\windoze>ruby test3.rb
test3.rb:14: [BUG] Segmentation fault
ruby 1.9.1p243 (2009-07-16 revision 24175) [i386-mingw32]

-- control frame ----------
c:0004 p:---- s:0013 b:0013 l:000012 d:000012 CFUNC  :GetLocalTime
c:0003 p:0049 s:0009 b:0008 l:001b14 d:001f24 EVAL   test3.rb:14
c:0002 p:---- s:0004 b:0004 l:000003 d:000003 FINISH
c:0001 p:0000 s:0002 b:0002 l:001b14 d:001b14 TOP
---------------------------
-- Ruby level backtrace information-----------------------------------------
test3.rb:14:in `GetLocalTime'
test3.rb:14:in `<main>'

Thanks,
-Charles

Constant Generator without a prefix

Would it be possible to add a condition to FFI::ConstantGenerator#dump_constants so that the join does not happen if there is no prefix?

--- a/lib/ffi/tools/const_generator.rb
+++ b/lib/ffi/tools/const_generator.rb
@@ -117,7 +117,7 @@ module FFI

def dump_constants(io)
  @constants.each do |name, constant|
-     name = [@prefix, name].join '.'
+     name = [@prefix, name].join '.' if @prefix
      io.puts "#{name} = #{constant.converted_value}"
  end
end

FFI::Struct.size doesn't respect offsets properly

class BITMAPFILEHEADER < FFI::Struct
  layout(
    :Type, :int16, 0,
    :Size, :int32, 2,
    :Reserved1, :int16, 6,
    :Reserved2, :int16, 8,
    :OffBits, :int32, 10
  )
end

(implementing http://msdn.microsoft.com/en-us/library/dd183374%28VS.85%29.aspx )

BITMAPFILEHEADER.layout returns #<FFI::Type:02E67BD0 size=16 alignment=4>.

The size should be 14, not 16.

The size should maybe be implemented to just look at the highest offset and add the size of that field? Highest offset 10 + size 4 gives the correct size for this struct.

Is there a way to override the alignment? Since that seems to be the issue here, telling it to align by 2 (or 1) instead of 4 would also give the correct size, I think (and then I wouldn't have to give explicit offsets for each member).

v0.5.4 and v0.5.0: Deprecated gcc flags & warnings are errors

Hi,

Trying to get ffi working on a stock CentOS5 system [gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-46)] but the native bits of the gem build fail to compile b/c of the warnings as errors flags, which yield dozens of warnings, ending with:

In v0.5.4:
gcc -I. -I. -I/usr/lib/ruby/1.8/i386-linux -I. -I/usr/lib/ruby/gems/1.8/gems/ffi-0.5.4/ext/ffi_c/libffi/include -DRUBY_EXTCONF_H="extconf.h" -fPIC -O2 -g -march=i386 -mcpu=i686 -Wall -fPIC -Werror -Wunused -Wformat -Wimplicit -Wreturn-type -c Call.c
-mcpu=' is deprecated. Use-mtune=' or '-march=' instead.
cc1: warnings being treated as errors
Call.c: In function ‘getString’:
Call.c:415: warning: control reaches end of non-void function
make: *** [Call.o] Error 1

In v0.5.0:
gcc -I. -I. -I/usr/lib/ruby/1.8/i386-linux -I. -I/usr/lib/ruby/gems/1.8/gems/ffi-0.5.0/ext/ffi_c/libffi/include -DHAVE_EXTCONF_H -Werror -Wunused -Wformat -Wimplicit -Wreturn-type -fPIC -O2 -g -march=i386 -mcpu=i686 -Wall -fPIC -c AbstractMemory.c
-mcpu=' is deprecated. Use-mtune=' or '-march=' instead.
cc1: warnings being treated as errors
AbstractMemory.c: In function ‘get_pointer_value’:
AbstractMemory.c:160: warning: control reaches end of non-void function
make: *** [AbstractMemory.o] Error 1

callback needs options

I don't know details...

ffi/lib/ffi/library.rb

def callback(*args)
  raise ArgError, "wrong number of arguments" if args.length < 2 || args.length > 3
  name, params, ret = if args.length == 3
    args
  else
    [ nil, args[0], args[1] ]
  end

  options = Hash.new
  options[:convention] = defined?(@ffi_convention) ? @ffi_convention : :default
  options[:enums] = @ffi_enums if defined?(@ffi_enums)
  options[:blocking] = @ffi_blocking if defined?(@ffi_blocking) # ?
  cb = FFI::CallbackInfo.new(find_type(ret), params.map { |e| find_type(e) }, options)

  # Add to the symbol -> type map (unless there was no name)
  unless name.nil?
    @ffi_callbacks = Hash.new unless defined?(@ffi_callbacks)
    @ffi_callbacks[name] = cb
  end

  cb
end

Can't build gem with Sun Studio compiler

~/Repositories/sys-uptime-> sudo gem install ffi
Password:
Building native extensions. This could take a while...
ERROR: Error installing ffi:
ERROR: Failed to build gem native extension.

/usr/local/bin/ruby extconf.rb
checking for #include <ffi.h>
... no
checking for ffi_call() in -lffi... no
checking for ffi_prep_closure()... no
checking for ffi_raw_call()... no
checking for rb_thread_blocking_region()... no
creating extconf.h
creating Makefile

make
make: Fatal error in reader: ./libffi.gnu.mk, line 15: Unexpected end of line seen

Gem files will remain installed in /usr/local/lib/ruby/gems/1.8/gems/ffi-0.5.4 for inspection.
Results logged to /usr/local/lib/ruby/gems/1.8/gems/ffi-0.5.4/ext/ffi_c/gem_make.out

~/Repositories/sys-uptime-> gem env
RubyGems Environment:

  • RUBYGEMS VERSION: 1.3.5
  • RUBY VERSION: 1.8.6 (2009-08-04 patchlevel 383) [i386-solaris2.10]
  • INSTALLATION DIRECTORY: /usr/local/lib/ruby/gems/1.8
  • RUBY EXECUTABLE: /usr/local/bin/ruby
  • EXECUTABLE DIRECTORY: /usr/local/bin
  • RUBYGEMS PLATFORMS:
    • ruby
    • x86-solaris-2.10
  • GEM PATHS:
    • /usr/local/lib/ruby/gems/1.8
    • /export/home/djberge/.gem/ruby/1.8
  • GEM CONFIGURATION:
    • :update_sources => true
    • :verbose => true
    • :benchmark => false
    • :backtrace => false
    • :bulk_threshold => 1000
  • REMOTE SOURCES:

Invalid CCFLAGS: -fno-common-Werror

Version 0.5.3, ext/ffi_c/Makefile has the CCFLAG "-fno-common-Werror", which I think should be "-fno-common -Werror" (with a space between the two flags). This causes an unrecognized command line option error.

gemspec missing some new files

These files are missing from the gemspec at the moment, causing gem install to fail.

ext/ffi_c/ClosurePool.c
ext/ffi_c/ClosurePool.h

ffi breaks everything if vendored

if ffi gets vendored in an rails project, as an dependency of capybara, then it just breaks rake in peaces.

  • PROJ - Constant not defined in all ffi Rakefiles.
    I had to remove all Rakefiles, and bundle my own version of ffi to get Rake working again.

Build failure on Red Hat Enterprise Linux 5.3

Don't see this on my local machine (Mac OS X 10.6), but I am seeing it on RHEL 5.3:

...
gcc -I. -I. -I/usr/lib/ruby/1.8/i386-linux -I. -I/home/rails.wincent.com/deploy/releases/20091126200856/vendor/gems/ffi-0.5.3/ext/ffi_c/libffi/include -DRUBY_EXTCONF_H=\"extconf.h\"  -fPIC -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -Wall -fno-strict-aliasing  -fPIC-Werror -Wunused -Wformat -Wimplicit -Wreturn-type   -c Pointer.c
cc1: error: unrecognized command line option "-fPIC-Werror"
make: *** [Pointer.o] Error 1

Notice how "-fPIC" and "-Werror" get mashed together, causing the error.

Adding an extra space at the start of "CFLAGS" in the extconf.rb makes it go away:

diff --git a/vendor/gems/ffi-0.5.3/ext/ffi_c/extconf.rb b/vendor/gems/ffi-0.5.3/ext/ffi_c/extconf.rb
index 08ef0b4..6e20fcb 100644
--- a/vendor/gems/ffi-0.5.3/ext/ffi_c/extconf.rb
+++ b/vendor/gems/ffi-0.5.3/ext/ffi_c/extconf.rb
@@ -18,7 +18,7 @@ $defs << "-DHAVE_EXTCONF_H" if $defs.empty? # needed so create_header works
 create_header

 $CFLAGS << "-mwin32 " if Config::CONFIG['host_os'] =~ /cygwin/
-$CFLAGS << "-Werror -Wunused -Wformat -Wimplicit -Wreturn-type "
+$CFLAGS << " -Werror -Wunused -Wformat -Wimplicit -Wreturn-type "

 create_makefile("ffi_c")
 unless libffi_ok

Could not install gem on FreeBSD

When installing gem an error occurs:

===> Installing for rubygem-ffi-0.5.0
===> rubygem-ffi-0.5.0 depends on file: /usr/local/bin/gem18 - found
===> rubygem-ffi-0.5.0 depends on file: /usr/local/bin/ruby18 - found
===> rubygem-ffi-0.5.0 depends on file: /usr/local/bin/ruby18 - found
===> Generating temporary packing list
===> Checking if devel/rubygem-ffi already installed
/usr/bin/env /usr/local/bin/gem18 install -l --no-update-sources --no-ri --install-dir /usr/local/lib/ruby/gems/1.8 /usr/distfiles/rubygem/ffi-0.5.0.gem -- --build-args
Building native extensions. This could take a while...
ERROR: Error installing /usr/distfiles/rubygem/ffi-0.5.0.gem:
ERROR: Failed to build gem native extension.

/usr/local/bin/ruby18 extconf.rb --build-args
checking for ffi_closure_alloc() in -lffi... no
checking for rb_thread_blocking_region()... no
creating Makefile
creating extconf.h

make
"./libffi.bsd.mk", line 12: Malformed conditional ("${srcdir}" == ".")
"./libffi.bsd.mk", line 14: if-less else
"./libffi.bsd.mk", line 16: if-less endif
make: fatal errors encountered -- cannot continue

Gem files will remain installed in /usr/local/lib/ruby/gems/1.8/gems/ffi-0.5.0 for inspection.
Results logged to /usr/local/lib/ruby/gems/1.8/gems/ffi-0.5.0/ext/ffi_c/gem_make.out
*** Error code 1

Here is content of gem_make.out:
/usr/local/bin/ruby18 extconf.rb --build-args
checking for ffi_closure_alloc() in -lffi... no
checking for rb_thread_blocking_region()... no
creating Makefile
creating extconf.h

make
"./libffi.bsd.mk", line 12: Malformed conditional ("${srcdir}" == ".")
"./libffi.bsd.mk", line 14: if-less else
"./libffi.bsd.mk", line 16: if-less endif
make: fatal errors encountered -- cannot continue

no long double support?

Just starting with ffi. Trying to wrap a library that contains the following:
typedef long double SmiFloat128;

There doesn't seem to be a :long_double type. How can I add that?

build failure on windows 7

gem install ffi
Building native extensions. This could take a while...
ERROR: Error installing ffi:
ERROR: Failed to build gem native extension.

C:/data/Ruby/bin/ruby.exe extconf.rb install ffi
checking for rb_thread_blocking_region()... no
creating extconf.h
creating Makefile

nmake

Microsoft (R) Program Maintenance Utility Version 9.00.30729.01
Copyright (C) Microsoft Corporation. All rights reserved.

makefile(183) : fatal error U1002: syntax error : invalid macro invocation '$'
Stop.

ENV:
windows 7
visual studio express 2008
ruby 1.8.6

ability to load multiple libraries

currently it appears you can only specify one library:

module Hello
  extend FFI::Library
  ffi_lib 'msvcrt'
  ffi_lib 'user32'

  ffi_convention :default
  attach_function 'FindWindowA', [ :string, :string], :pointer
end

fails if you switch the ffi_lib commands.

<FFI::NotFoundError: Function 'FindWindowA' not found in [msvcrt]>

It would be convenient if you could specify more than one.
a la

<FFI::NotFoundError: Function 'FindWindowA' not found in [msvcrt, user32]>

etc.

attach_function Documentation Incorrect

lib/ffi/library.rb line 99

The documentation in the source for attach_function is incorrect. It states that if you want an alternate name for the method, you have to specify it after the +name+ when, in fact, you have to specify it before the +name+.

Sorry I cannot provide a patch, I do not have time right now to and this is a simple wording fix.

Failure to attach callback due to compile flag

I am defining a callback to ruby that gets registered with a C library. To do so I'm using the callback api. In 0.5.0 the callback works, but in the current 0.6.0 branch it does not. The attachment breaks at 8cbc3f5, during which some of the compile flags in extconf.rb got changed.

I found I could make the callback work again by messing with the compile flags in a local copy. I did the following:

  • checkout 610fedd
  • rake test (all passes)
  • ran the test script (fails)
  • change the extconf.rb as below
  • rake test (all passes)
  • ran the test script (passes)

All of this was done on OS X 10.5.8.

Test Script

module Foo
  extend FFI::Library
  ffi_lib 'path/to/my.bundle'

  callback :my_callback, [], :int
  attach_function :InitializeEnvironment, [], :void 
  attach_function :DefineFunction, [ :string, :char, :my_callback, :string ], :int
end

cb = Proc.new { 0 }
Foo.InitializeEnvironment
res = Foo.DefineFunction("ruby-callback", ?d, cb, "RubyCallback")
puts(res == 1 ? 'pass' : 'fail')

The updated extconf.rb

...
$defs << "-DHAVE_EXTCONF_H" if $defs.empty? # needed so create_header works
$defs << "-DHAVE_RAW_API"        # This is what I added
create_header
...

typo in platform.rb?

line 22 defines ARCH but the exception case on line 30 refers to "ARCH_" with an underscore

char attach_variable - can't convert String into Integer (TypeError)

Hello,

I'm using ffi (0.5.1) with ruby 1.8.6 (2009-08-04 patchlevel 383) [i686-linux].

I have the following example.rb file:

require 'ffi'

module Example
  extend FFI::Library
  ffi_lib './example.so'

  attach_variable :cvar, :char
end

When I try to assign to that attached variable:

 Example.cvar   =  "S"

I get this error:

% ruby -rubygems runme.rb
(eval):6:in `[]=': can't convert String into Integer (TypeError)
  from (eval):6:in `cvar='
  from runme.rb:15

Shouldn't FFI do "S"[0,1].ord to get the integer value?

Also, why the (eval) in the error backtrace? Please see this patch.

Thanks for your consideration.

FFI::Struct layout does not handle Arrays of Structs properly.

When defining a layout for a C Struct that contains an inline Array of other Structs, FFI 0.5.3 will raise this exception:

/usr/lib64/ruby/gems/1.8/gems/ffi-0.5.3/lib/ffi/struct.rb:175:in `initialize': wrong argument type Class (expected Data) (TypeError)
    from /usr/lib64/ruby/gems/1.8/gems/ffi-0.5.3/lib/ffi/struct.rb:175:in `add_array'
    from /usr/lib64/ruby/gems/1.8/gems/ffi-0.5.3/lib/ffi/struct.rb:175:in `array_layout'
    from /usr/lib64/ruby/gems/1.8/gems/ffi-0.5.3/lib/ffi/struct.rb:106:in `layout'
    from /underground/code/sophsec/ffi-udis86/lib/udis86/ud.rb:14

I found the line of code which was triggering the exception was:

  ud.rb:32:             :operand, [Operand, 3],

UD: http://github.com/sophsec/ffi-udis86/blob/master/lib/udis86/ud.rb
Operand: http://github.com/sophsec/ffi-udis86/blob/master/lib/udis86/operand.rb

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.