1

I had used Ruby 1.9 long ago and now I am trying Ruby 3.2 Fiddle. I tried the following snippet in the README.md, but it raised a NameError on the struct.

StudentCollegeDetail = struct [
  'int college_id',
  'char college_name[50]'
]

How can I use that struct? Where is the documentation of it?

relent95
  • 3,703
  • 1
  • 14
  • 17

1 Answers1

2

Well, it was a stupid question. You can use the struct like this.

require 'fiddle/import'

StudentCollegeDetail = Fiddle::Importer::struct [
  'int college_id',
  'char college_name[50]'
]

The documentation is at this.

As commented by Holger, the Fiddle::Importer is designed to be used as an argument of the extend() inside a module like this.

require 'fiddle/import'

module Libc
  extend Fiddle::Importer
  dlload 'libc.so.6'
  typealias 'clockid_t', 'int'
  typealias 'time_t', 'int64_t'
  Timespec = struct [
    'time_t   tv_sec',
    'long     tv_nsec',
  ]
  extern 'int clock_getres(clockid_t clk_id, struct timespec *res);'
end

res = Libc::Timespec.malloc
Libc.clock_getres(Process::CLOCK_REALTIME, res)
p res.tv_nsec
relent95
  • 3,703
  • 1
  • 14
  • 17
  • 1
    The idea of the `Fiddle::Importer` module is in fact intended to use it as shown in the example, i.e. that you define your own module/class and extend it with `Fiddle::Importer`. Then, have all the helper methods available in your class/module context to import and define methods from the external libraries. – Holger Just May 26 '23 at 12:48
  • 2
    Also, the [documentation for newer versions of Ruby and fiddle](https://docs.ruby-lang.org/en/3.2/Fiddle/Importer.html) has become better. – Holger Just May 26 '23 at 12:50
  • @Holger, thanks for the comments. I added a detail on the ```Importer```. – relent95 May 27 '23 at 05:51