0

Simple case, something like printf(str, [arg1, arg2, ...])

How would I write a ruby 'attach_function' call using FFI to utilize such a function?

I'm surprised that I can't find this question answered through my googling, but perhaps I'm using the wrong terminology.

-- update -- Perhaps I was not clear enough. I am already in the middle of writing a RubyGem that interfaces with a C library. Its working just fine already. I'm using FFI and was going along just fine until I hit this function with a variable argument list.

1 Answer 1

2

The canonical way to use a C function in ruby is to extend ruby through creating a gem for it. There is no straight forward method like Haskell has.

However, writing a C gem for ruby is a fairly easy task, almost as easy as use a FFI in Haskell. You can see this free chapter from ruby pickaxe that teaches how to create a simple C gem, and should be enough to get going.

edit

If your problem is with varargs and ffi, assuming you are using the ffi gem, you can look the examples on documentation, where this example shows how to do it:

require 'ffi'

module Hello
  extend FFI::Library
  attach_function 'printf', [:string, :varargs], :int
end

3.times {  Hello.printf("cputs %s %d %x", :string, "yoyo", :int, 33, :int, 34)} # each one needs its own specifier of which type it is

If you try this and didn't work, let us see your code and tell us what went wrong

Sign up to request clarification or add additional context in comments.

5 Comments

I specifically mentioned FFI for Ruby.
@BadQuanta My bad, fixed the answer. However, if you are already writing a gem, will answer only your curiosity.
Thank you so much, this was the answer I needed. I kept googling for "FFI Ruby Variable Arguments" and completely overlooked that section of the docs.
@BadQuanta Happy to help. As odd as it seems, these functions are called variadic or simply varargs - this might help you in your next googles.
This example code did not work here. There is an error: LoadError: no library specified However, I just included the default C library via ffi_lib 'c' inside the Hello module and, after that, the code worked fine here. Very good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.