Any way to use FFI on Ruby itself?

50 views
Skip to first unread message

Benjamin Fleischer

unread,
Nov 4, 2014, 11:55:54 PM11/4/14
to ruby...@googlegroups.com
I was curious if I could get access to the c-functions used in the Coverage module via FFI


Thus far I haven't figured out what the correct requires would be, or if it is possible. (I don't really know C)

require 'ffi'
require 'coverage.so'

module Coverage
  extend FFI::Library
  ffi_lib 'ruby'
  attach_function :rb_get_coverages, [], :int
  attach_function :rb_reset_coverages, [], :void
  typedef :pointer, :rb_coverages
end

puts Coverage.rb_get_coverages

yields a segfault

c:0004 p:---- s:0012 b:0012 l:000011 d:000011 CFUNC  :rb_reset_coverages 

c:0003 p:0188 s:0009 b:0008 l:0006a8 d:0003b8 EVAL   ffi.rb:22  

c:0002 p:---- s:0004 b:0004 l:000003 d:000003 FINISH 

c:0001 p:0000 s:0002 b:0002 l:0006a8 d:0006a8 TOP 


Or maybe I'm approaching it wrong and I should write a simple c extension?

I appreciate any pointers. If RTFM, link to right page would be great :)

-Benjamin

Matijs van Zuijlen

unread,
Nov 7, 2014, 4:07:23 AM11/7/14
to ruby...@googlegroups.com
Hi Benjamin,

On 05/11/14 05:55, Benjamin Fleischer wrote:
> I was curious if I could get access to the c-functions used in the Coverage
> module via FFI
>
> https://github.com/ruby/ruby/blob/trunk/ext/coverage/coverage.c#L69
>
> Thus far I haven't figured out what the correct requires would be, or if it is
> possible. (I don't really know C)
>
> require 'ffi'
> require 'coverage.so'

You're loading the coverage module which you're also going to access using ffi.

> module Coverage

This means that here, you're using the same module defined in coverage.so. I
would first try with a different name, or just not require 'coverage'.

> extend FFI::Library
> ffi_lib 'ruby'

rb_get_coverages is not defined in libruby.so. You should probably use ffi_lib
'coverage'. Possibly, you even need to include the whole file.

> attach_function :rb_get_coverages, [], :int
> attach_function :rb_reset_coverages, [], :void
> typedef :pointer, :rb_coverages
> end
>
> puts Coverage.rb_get_coverages

You're calling rb_get_coverages ...

> yields a segfault
>
> c:0004 p:---- s:0012 b:0012 l:000011 d:000011 CFUNC :rb_reset_coverages

... but the segfault is in in rb_reset_coverages. It may be worthwhile to figure
out exactly where in the above example the segfault occurs.

> c:0003 p:0188 s:0009 b:0008 l:0006a8 d:0003b8 EVAL ffi.rb:22
>
> c:0002 p:---- s:0004 b:0004 l:000003 d:000003 FINISH
>
> c:0001 p:0000 s:0002 b:0002 l:0006a8 d:0006a8 TOP
>
>
> Or maybe I'm approaching it wrong and I should write a simple c extension?
>
> I appreciate any pointers. If RTFM, link to right page would be great :)
>
> -Benjamin

Regards,

--
Matijs

signature.asc

Benjamin Fleischer

unread,
Dec 2, 2014, 1:48:26 AM12/2/14
to ruby...@googlegroups.com
Just saw this, will try.
Reply all
Reply to author
Forward
0 new messages