module YARP::LibRubyParser
Public Class Methods
load_exported_functions_from(header, *functions)
click to toggle source
Read through the given header file and find the declaration of each of the given functions. For each one, define a function with the same name and signature as the C function.
# File yarp/ffi.rb, line 35 def self.load_exported_functions_from(header, *functions) File.foreach(File.expand_path("../../include/#{header}", __dir__)) do |line| # We only want to attempt to load exported functions. next unless line.start_with?("YP_EXPORTED_FUNCTION ") # We only want to load the functions that we are interested in. next unless functions.any? { |function| line.include?(function) } # Parse the function declaration. unless /^YP_EXPORTED_FUNCTION (?<return_type>.+) (?<name>\w+)\((?<arg_types>.+)\);$/ =~ line raise "Could not parse #{line}" end # Delete the function from the list of functions we are looking for to # mark it as having been found. functions.delete(name) # Split up the argument types into an array, ensure we handle the case # where there are no arguments (by explicit void). arg_types = arg_types.split(",").map(&:strip) arg_types = [] if arg_types == %w[void] # Resolve the type of the argument by dropping the name of the argument # first if it is present. arg_types.map! { |type| resolve_type(type.sub(/\w+$/, "")) } # Attach the function using the FFI library. attach_function name, arg_types, resolve_type(return_type) end # If we didn't find all of the functions, raise an error. raise "Could not find functions #{functions.inspect}" unless functions.empty? end
resolve_type(type)
click to toggle source
Convert a native C type declaration into a symbol that FFI understands. For example:
const char * -> :pointer bool -> :bool size_t -> :size_t void -> :void
# File yarp/ffi.rb, line 27 def self.resolve_type(type) type = type.strip.delete_prefix("const ") type.end_with?("*") ? :pointer : type.to_sym end