How can I pass a FILE * to stdin/stdout to a C function via Ruby's Fiddle?

36 Views Asked by At

I'm trying to interface with an ncurses library (Thomas Dickey's dialog to be precise) using Fiddle and I need to pass FILE pointers for stdin and stdout to the library, but everything I try results in a segfault. Here is an example of one thing I tried:

require_relative "my_module/version"
require 'fiddle'
require 'fiddle/import'

module MyModule
  extend Fiddle::Importer

  # Load the dialog library
  dlload '/usr/local/lib/libdialog.dylib' # Replace with the appropriate library name on your system

  # Include the dialog header
  extern 'int dialog_yesno(const char *, const char *, int, int)'
  extern 'int init_dialog(FILE *, FILE *)'
  extern 'void end_dialog(void)'

  # Initialize and terminate the dialog library
  def self.with_dialog
    stdin_fd = IO.sysopen('/dev/stdin', 'r')
    stdout_fd = IO.sysopen('/dev/stdout', 'w')
    stdin_pointer = Fiddle.dlwrap(stdin_fd.to_i) # Create a pointer for stdin
    stdout_pointer = Fiddle.dlwrap(stdout_fd.to_i) # Create a pointer for stdout
    init_dialog(stdin_pointer, stdout_pointer)
    yield
  ensure
    end_dialog
  end

  MyModule.with_dialog do
    result = MyModule.dialog_yesno("Do you want to proceed?", "", 10, 40)
    puts "Result: #{result}"
  end
end

I've tried a bunch of stuff, using the Fiddle pointer, I just get nowhere segfaults every time. I feel like I am just doing it wrong. Anybody got any ideas?

Tried several different ways to pass pointers to stdin/stdout, got segfaults. Expect a dialog box.

0

There are 0 best solutions below