4

I have to load several functions that return structures from the library itself.

attach_function 'fn_name', [], # ... What do I put here?

RubyFFI's Wiki pages seem to be outdated, so I'm a little lost here.

How do I create a FFI::Struct, and how do I specify it as the return type of a native function?

Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107

1 Answers1

8
class SOME_STRUCT < FFI::Struct 
    layout :a, :float, 
           :b, :float
end

and then

attach_function 'fn_name', [], SOME_STRUCT

and if it stack-allocated struct:

typedef struct
{ 
    float a, b; 
} SOME_STRUCT;

you should use this:

attach_function 'fn_name', [], SOME_STRUCT.by_value
Vasiliy Ermolovich
  • 24,459
  • 5
  • 79
  • 77
  • 4
    As of ffi-1.0 (and JRuby 1.6.0), use SOME_STRUCT.by_ref as the return type if the function returns a reference to a struct - when you just use SOME_STRUCT, you get back a FFI::Pointer instead of an instance of SOME_STRUCT. You can also use the shorthand SOME_STRUCT.ptr, and SOME_STRUCT.val - whichever floats your boat. –  Mar 23 '11 at 04:09